0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】Readonly<T>の自作(type-challenges 初級編 7・Readonly)

Last updated at Posted at 2024-12-06

お題

Tのすべてのプロパティを読み取り専用にする型MyReadonlyを実装する。プロパティの再割り当てはできない(読み取り専用にする)。

やりたいこと

type Person = {
  surname: string;
  middleName: string;
  givenName: string;
};

type ReadonlyPerson = MyReadonly<Person>;

type ReadonlyPerson = {
    readonly surname: string;
    readonly middleName: string;
    readonly givenName: string;
}

解答

MyReadonly<T> = { readonly [key in keyof T] : T[key] }

解説

処理の流れ

  • { readonly … }
    readonly修飾子を付け、プロパティを読み取り専用にする。
  • [key in keyof T] : T[key]
    Mapped Typesとkeyof演算子を利用し、新しいオブジェクト型を作成。

readonly修飾子とは...

  • オブジェクトのプロパティを読み取り専用にすることができる。
let obj: {
  readonly foo: number;
};

obj = { foo: 1 };
obj.foo = 2; // Cannot assign to 'foo' because it is a read-only property.
  • readonlyは再帰的ではない。
    → オブジェクトが入れ子になっている場合、その中のオブジェクトまではreadonlyにはならないので注意が必要。

Mapped Typesとは...

keyof演算子とは...

参考記事

Readonly<T>

readonly修飾子

今回の問題

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?