Mapped Typesについて
Mapped Typesについて
既存の型を元に動的に新しい型を作る方法を提供する
構文
{[P in K]: T}
- P はこのMapped Typeの引数型 (parameter type)
- K はこのMapped Typeの制約型 (constraint type)
- T はこのMapped Typeのテンプレート型 (template type)
下記の定義に似てる
type Element<P extends K> = T;
例)
type Item = { a: string, b: number, c: boolean }; type T1 = { [P in "x" | "y"]: number }; // { x: number, y: number } type T2 = { [P in "x" | "y"]: P }; // { x: "x", y: "y" } type T3 = { [P in "a" | "b"]: Item[P] }; // { a: string, b: number } type T4 = { [P in keyof Item]: Date }; // { a: Date, b: Date, c: Date } type T5 = { [P in keyof Item]: Item[P] }; // { a: string, b: number, c: boolean } type T6 = { readonly [P in keyof Item]: Item[P] }; // { readonly a: string, readonly b: number, readonly c: boolean } type T7 = { [P in keyof Item]: Array<Item[P]> }; // { a: string[], b: number[], c: boolean[] }
具体的な使い方
型Artistから型ArtistForEditのような型を生成する場合
interface Artist { id: number; name: string; bio: string; }
interface ArtistForEdit { id: number; name?: string; bio?: string; }
こんな感じで型を生成できる
// Mapped Typesでプロパティを変更(必須⇒任意)してから、交差型を使ってidのみ必須とする type MyPartialType<T> = { [P in keyof T]?: T[P]; } & { id: number }; type MappedArtistForEdit = MyPartialType<Artist>; const obj:MappedArtistForEdit = { id: 123 };