TypeScript の 型レベルJSONスキーマ

レベル 5527 打鍵

再帰的な条件型が JSON スキーマ風の小さなオブジェクトを読み取り、対応する TypeScript の型を求めます。as const を使うと、下のスキーマは { readonly name: string } という型になります。

TypeScript のコード

// スキーマは string、number、またはネストしたスキーマを持つ object
1type Schema = { type: "string" } | { type: "number" } | { type: "object"; properties: Record<string, Schema> };
// type フィールドを1ケースずつ調べる
2type Infer<S extends Schema> = S extends { type: "string" }
// "string" → string
3 ? string
4 : S extends { type: "number" }
// "number" → number
5 ? number
// "object" ならプロパティ P を推論する
6 : S extends { type: "object"; properties: infer P }
// 各プロパティの型を再帰的に求める
7 ? { [K in keyof P]: P[K] extends Schema ? Infer<P[K]> : never }
8 : never;
// as const で "object" や "string" をリテラル型のまま保つ
9const schema = { type: "object", properties: { name: { type: "string" } } } as const;
// { readonly name: string } になる
10type User = Infer<typeof schema>;
// name は string でなければならない。数値ではコンパイルできない
11const user: User = { name: "Alice" };
// 「Alice」を表示する
12console.log(user.name);

実行結果

Alice
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この TypeScript のコードで打つ記号と、出てくる回数です。

  • :× 19
  • "× 18
  • {× 11
  • }× 11
  • ;× 8
  • =× 5
  • ?× 4
  • <× 4
  • >× 4
  • [× 3

TypeScript のレベル 5 のほかのコード例

← TypeScript タイピング練習のトップへ