TypeScript 提供了多種工具型別來幫助進行常見的型別轉換。這些工具在全域性範圍內均可使用。
Awaited<Type>
釋出版本: 4.5
此型別旨在模擬 async 函式中的 await 操作,或 Promise 上的 .then() 方法——具體來說,就是遞迴解包 Promise 的方式。
示例
tsTrytypeA =Awaited <Promise <string>>;typeB =Awaited <Promise <Promise <number>>>;typeC =Awaited <boolean |Promise <number>>;
Partial<Type>
已釋出
2.1
構造一個型別,將 Type 的所有屬性設定為可選。該工具將返回一個表示給定型別的所有子集的型別。
示例
tsTryinterfaceTodo {title : string;description : string;}functionupdateTodo (todo :Todo ,fieldsToUpdate :Partial <Todo >) {return { ...todo , ...fieldsToUpdate };}consttodo1 = {title : "organize desk",description : "clear clutter",};consttodo2 =updateTodo (todo1 , {description : "throw out trash",});
Required<Type>
已釋出
2.8
構造一個由 Type 的所有屬性組成的型別,並將它們設定為必填。與 Partial 相反。
示例
tsTryinterfaceProps {a ?: number;b ?: string;}constobj :Props = {a : 5 };constProperty 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.: obj2 Required <Props > = {a : 5 };
Readonly<Type>
已釋出
2.1
構造一個型別,將 Type 的所有屬性設定為 readonly,這意味著構造型別的屬性不能被重新賦值。
示例
tsTryinterfaceTodo {title : string;}consttodo :Readonly <Todo > = {title : "Delete inactive users",};Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.todo .= "Hello"; title
該工具對於表示在執行時會失敗的賦值表示式(例如,嘗試重新賦值 凍結物件 (frozen object) 的屬性)非常有用。
Object.freeze
tsfunction freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys, Type>
已釋出
2.1
構造一個物件型別,其屬性鍵為 Keys,屬性值為 Type。此工具可用於將一種型別的屬性對映到另一種型別。
示例
tsTrytypeCatName = "miffy" | "boris" | "mordred";interfaceCatInfo {age : number;breed : string;}constcats :Record <CatName ,CatInfo > = {miffy : {age : 10,breed : "Persian" },boris : {age : 5,breed : "Maine Coon" },mordred : {age : 16,breed : "British Shorthair" },};cats .boris ;
Pick<Type, Keys>
已釋出
2.1
透過從 Type 中拾取一組屬性 Keys(字串字面量或字串字面量的聯合型別)來構造一個型別。
示例
tsTryinterfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Pick <Todo , "title" | "completed">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Omit<Type, Keys>
已釋出
3.5
透過從 Type 中拾取所有屬性,然後刪除 Keys(字串字面量或字串字面量的聯合型別)來構造一個型別。與 Pick 相反。
示例
tsTryinterfaceTodo {title : string;description : string;completed : boolean;createdAt : number;}typeTodoPreview =Omit <Todo , "description">;consttodo :TodoPreview = {title : "Clean room",completed : false,createdAt : 1615544252770,};todo ;typeTodoInfo =Omit <Todo , "completed" | "createdAt">;consttodoInfo :TodoInfo = {title : "Pick up kids",description : "Kindergarten closes at 5pm",};todoInfo ;
Exclude<UnionType, ExcludedMembers>
已釋出
2.8
透過從 UnionType 中排除所有可分配給 ExcludedMembers 的聯合成員來構造一個型別。
示例
tsTrytypeT0 =Exclude <"a" | "b" | "c", "a">;typeT1 =Exclude <"a" | "b" | "c", "a" | "b">;typeT2 =Exclude <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT3 =Exclude <Shape , {kind : "circle" }>
Extract<Type, Union>
已釋出
2.8
透過從 Type 中提取所有可分配給 Union 的聯合成員來構造一個型別。
示例
tsTrytypeT0 =Extract <"a" | "b" | "c", "a" | "f">;typeT1 =Extract <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT2 =Extract <Shape , {kind : "circle" }>
NonNullable<Type>
已釋出
2.8
透過從 Type 中排除 null 和 undefined 來構造一個型別。
示例
tsTrytypeT0 =NonNullable <string | number | undefined>;typeT1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
已釋出
3.1
從函式型別 Type 的引數中使用的型別構造一個元組型別。
對於過載函式,這將是最後一個簽名的引數;參見 條件型別中的型別推斷。
示例
tsTrydeclare functionf1 (arg : {a : number;b : string }): void;typeT0 =Parameters <() => string>;typeT1 =Parameters <(s : string) => void>;typeT2 =Parameters <<T >(arg :T ) =>T >;typeT3 =Parameters <typeoff1 >;typeT4 =Parameters <any>;typeT5 =Parameters <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T6 =Parameters <string >;typeType 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.T7 =Parameters <>; Function
ConstructorParameters<Type>
已釋出
3.1
從建構函式型別的型別構造一個元組或陣列型別。它產生一個包含所有引數型別的元組型別(如果 Type 不是函式,則為 never 型別)。
示例
tsTrytypeT0 =ConstructorParameters <ErrorConstructor >;typeT1 =ConstructorParameters <FunctionConstructor >;typeT2 =ConstructorParameters <RegExpConstructor >;classC {constructor(a : number,b : string) {}}typeT3 =ConstructorParameters <typeofC >;typeT4 =ConstructorParameters <any>;typeType 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.T5 =ConstructorParameters <>; Function
ReturnType<Type>
已釋出
2.8
構造一個由函式 Type 的返回型別組成的型別。
對於過載函式,這將是最後一個簽名的返回型別;參見 條件型別中的型別推斷。
示例
tsTrydeclare functionf1 (): {a : number;b : string };typeT0 =ReturnType <() => string>;typeT1 =ReturnType <(s : string) => void>;typeT2 =ReturnType <<T >() =>T >;typeT3 =ReturnType <<T extendsU ,U extends number[]>() =>T >;typeT4 =ReturnType <typeoff1 >;typeT5 =ReturnType <any>;typeT6 =ReturnType <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T7 =ReturnType <string >;typeType 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.T8 =ReturnType <>; Function
InstanceType<Type>
已釋出
2.8
構造一個由 Type 中的建構函式的例項型別組成的型別。
示例
tsTryclassC {x = 0;y = 0;}typeT0 =InstanceType <typeofC >;typeT1 =InstanceType <any>;typeT2 =InstanceType <never>;typeType 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.T3 =InstanceType <string >;typeType 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.T4 =InstanceType <>; Function
NoInfer<Type>
已釋出
5.4
阻止對包含的型別進行推斷。除了阻止推斷外,NoInfer<Type> 與 Type 完全相同。
示例
tsfunction createStreetLight<C extends string>(colors: C[],defaultColor?: NoInfer<C>,) {// ...}createStreetLight(["red", "yellow", "green"], "red"); // OKcreateStreetLight(["red", "yellow", "green"], "blue"); // Error
ThisParameterType<Type>
已釋出
3.3
提取函式型別的 this 引數型別,如果函式型別沒有 this 引數,則返回 unknown。
示例
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
已釋出
3.3
從 Type 中刪除 this 引數。如果 Type 沒有顯式宣告 this 引數,則結果僅為 Type。否則,將從 Type 建立一個新的沒有 this 引數的函式型別。泛型會被擦除,只有最後一個過載簽名會被傳播到新的函式型別中。
示例
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);console .log (fiveToHex ());
ThisType<Type>
已釋出
2.3
此工具不返回轉換後的型別。相反,它用作上下文 this 型別的標記。注意,必須啟用 noImplicitThis 標誌才能使用此工具。
示例
tsTrytypeObjectDescriptor <D ,M > = {data ?:D ;methods ?:M &ThisType <D &M >; // Type of 'this' in methods is D & M};functionmakeObject <D ,M >(desc :ObjectDescriptor <D ,M >):D &M {letdata : object =desc .data || {};letmethods : object =desc .methods || {};return { ...data , ...methods } asD &M ;}letobj =makeObject ({data : {x : 0,y : 0 },methods : {moveBy (dx : number,dy : number) {this.x +=dx ; // Strongly typed thisthis.y +=dy ; // Strongly typed this},},});obj .x = 10;obj .y = 20;obj .moveBy (5, 5);
在上面的示例中,makeObject 引數中的 methods 物件具有一個包含 ThisType<D & M> 的上下文型別,因此 methods 物件內方法的 this 型別為 { x: number, y: number } & { moveBy(dx: number, dy: number): void }。注意 methods 屬性的型別是如何同時成為推斷目標以及方法中 this 型別來源的。
ThisType<T> 標記介面僅僅是在 lib.d.ts 中宣告的一個空介面。除了在物件字面量的上下文型別中被識別外,該介面的作用就像任何空介面一樣。
內在字串操作型別
Uppercase<StringType>
Lowercase<StringType>
Capitalize<StringType>
Uncapitalize<StringType>
為了輔助模板字串字面量的字串操作,TypeScript 包含了一組可在型別系統中用於字串操作的型別。你可以在 模板字面量型別 文件中找到它們。