TypeScript の 型レベルJSONスキーマ
レベル 5527 打鍵
再帰的な条件型が JSON スキーマ風の小さなオブジェクトを読み取り、対応する TypeScript の型を求めます。as const を使うと、下のスキーマは { readonly name: string } という型になります。
TypeScript のコード
// スキーマは string、number、またはネストしたスキーマを持つ object1type Schema = { type: "string" } | { type: "number" } | { type: "object"; properties: Record<string, Schema> };// type フィールドを1ケースずつ調べる2type Infer<S extends Schema> = S extends { type: "string" } // "string" → string3 ? string4 : S extends { type: "number" } // "number" → number5 ? 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