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】type-challenges 中級編 9・Deep Readonly 解説

Posted at

お題

オブジェクトのすべてのパラメーター(およびそのサブオブジェクトを再帰的に)読み取り専用にする型DeepReadonlyを実装する。

やりたいこと

type Example = {
  x: {
    a: 1
    b: 'hi'
  }
  y: 'hey'
}

type Result = DeepReadonly<Example>;

// Result
type Result = {
  readonly x: {
    readonly a: 1
    readonly b: 'hi'
  }
  readonly y: 'hey'
}

解答

type DeepReadonly<T> = keyof T extends never 
  ? T
  : { readonly [K in keyof T]: DeepReadonly<T[K]> };

解説

処理の流れ

  • keyof T extends never ? T : ...
    keyof TneverであればTをそのまま返す条件分岐
  • { readonly [K in keyof T]: DeepReadonly<T[K]> }
    Mapped Typesを使用し、keyof Tneverになるまで再帰的に処理を行う

keyof Tがneverを返すタイミングはいつ?

Tプリミティブ型・リテラル型の場合にneverが返される。

Readonlyとは...

keyofとは...

Mapped Typesとは...

参考記事

今回の問題

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?