上級 › Mapped typeも通常と同じ型チェックを受ける理由 › パターン4
Mapped typeも通常と同じ型チェックを受ける理由
{ [K in keyof T]?: T[K] }のようなmapped typeで生成した型は、見た目は特殊でも、実体は通常のinterfaceと同じようにプロパティごとの型チェックが行われます。
1 interface Prefs { 2 theme: string; 3 volume: number; 4 } 5 type PartialPrefs = { [K in keyof Prefs]?: Prefs[K] }; 6 const p: PartialPrefs = { theme: "dark", volume: ___ }; ^ 7 console.log(p);
main.ts(6,42): error TS2322: Type 'string' is not assignable to type 'number'.
空欄を埋めてコンパイルを通す
PartialPrefsはPrefsの各プロパティをoptionalにしただけで、型自体はPrefs[K]のまま維持されます。
次の問題