自分自身を繰り返したくない場合は、型を別の型に基づかせる必要があります。
マップ型はインデックスシグネチャの構文に基づいて構築されます。インデックスシグネチャは、事前に宣言されていないプロパティの型を宣言するために使用されます。
tsTry
typeOnlyBoolsAndHorses = {[key : string]: boolean |Horse ;};constconforms :OnlyBoolsAndHorses = {del : true,rodney : false,};
マップ型は、`PropertyKey`のユニオン(多くの場合、`keyof`を介して作成されます)を使用してキーを反復処理し、型を作成するジェネリック型です。
tsTry
typeOptionsFlags <Type > = {[Property in keyofType ]: boolean;};
この例では、`OptionsFlags`は型`Type`からすべてのプロパティを取得し、それらの値をブール値に変更します。
tsTry
typeFeatures = {darkMode : () => void;newUserProfile : () => void;};typeFeatureOptions =OptionsFlags <Features >;
マッピング修飾子
マッピング中に適用できる2つの追加の修飾子があります。`readonly`と`?`は、それぞれ変更可能性とオプション性に影響します。
`-`または`+`を前に付けることで、これらの修飾子を削除または追加できます。接頭辞を追加しない場合、`+`が想定されます。
tsTry
// Removes 'readonly' attributes from a type's propertiestypeCreateMutable <Type > = {-readonly [Property in keyofType ]:Type [Property ];};typeLockedAccount = {readonlyid : string;readonlyname : string;};typeUnlockedAccount =CreateMutable <LockedAccount >;
tsTry
// Removes 'optional' attributes from a type's propertiestypeConcrete <Type > = {[Property in keyofType ]-?:Type [Property ];};typeMaybeUser = {id : string;name ?: string;age ?: number;};typeUser =Concrete <MaybeUser >;
`as`によるキー再マッピング
TypeScript 4.1以降では、マップ型で`as`句を使用してキーを再マップできます。
ts
type MappedTypeWithNewProperties<Type> = {[Properties in keyof Type as NewKeyType]: Type[Properties]}
テンプレートリテラル型などの機能を活用して、以前のプロパティ名から新しいプロパティ名を作成できます。
tsTry
typeGetters <Type > = {[Property in keyofType as `get${Capitalize <string &Property >}`]: () =>Type [Property ]};interfacePerson {name : string;age : number;location : string;}typeLazyPerson =Getters <Person >;
条件付き型を介して`never`を生成することにより、キーを除外できます。
tsTry
// Remove the 'kind' propertytypeRemoveKindField <Type > = {[Property in keyofType asExclude <Property , "kind">]:Type [Property ]};interfaceCircle {kind : "circle";radius : number;}typeKindlessCircle =RemoveKindField <Circle >;
`string | number | symbol`のユニオンだけでなく、任意の型のユニオンをマップできます。
tsTry
typeEventConfig <Events extends {kind : string }> = {[E inEvents asE ["kind"]]: (event :E ) => void;}typeSquareEvent = {kind : "square",x : number,y : number };typeCircleEvent = {kind : "circle",radius : number };typeConfig =EventConfig <SquareEvent |CircleEvent >
詳細
マップ型はこの型の操作セクションの他の機能とうまく連携します。たとえば、条件付き型を使用したマップ型は、オブジェクトにプロパティ`pii`がリテラル`true`に設定されているかどうかによって、`true`または`false`を返します。
tsTry
typeExtractPII <Type > = {[Property in keyofType ]:Type [Property ] extends {pii : true } ? true : false;};typeDBFields = {id : {format : "incrementing" };name : {type : string;pii : true };};typeObjectsNeedingGDPRDeletion =ExtractPII <DBFields >;