當您不希望重複時,有時一個類型需要建立在另一個類型之上。
對映類型建立在索引簽章的語法上,用於宣告尚未預先宣告的屬性類型
tsTrytypeOnlyBoolsAndHorses = {[key : string]: boolean |Horse ;};constconforms :OnlyBoolsAndHorses = {del : true,rodney : false,};
對映類型是一種泛型類型,它使用 PropertyKey 的聯集(通常透過 keyof 建立)來反覆處理鍵以建立類型
tsTrytypeOptionsFlags <Type > = {[Property in keyofType ]: boolean;};
在此範例中,OptionsFlags 會採用類型 Type 中的所有屬性,並將其值變更為布林值。
tsTrytypeFeatures = {darkMode : () => void;newUserProfile : () => void;};typeFeatureOptions =OptionsFlags <Features >;
對映修改器
在對映期間可以套用兩個額外的修改器: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 子句重新對應對映類型中的鍵
tstype MappedTypeWithNewProperties<Type> = {[Properties in keyof Type as NewKeyType]: Type[Properties]}
您可以利用 範本字串類型 等功能,從先前的屬性名稱建立新的屬性名稱
tsTrytypeGetters <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 的聯集,而是任何類型的聯集
tsTrytypeEventConfig <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 >
進一步探索
映射類型適用於此類型操作區段中的其他功能,例如這裡是 使用條件類型的映射類型,它會傳回 true 或 false,視物件是否將屬性 pii 設定為文字 true
tsTrytypeExtractPII <Type > = {[Property in keyofType ]:Type [Property ] extends {pii : true } ? true : false;};typeDBFields = {id : {format : "incrementing" };name : {type : string;pii : true };};typeObjectsNeedingGDPRDeletion =ExtractPII <DBFields >;