TypeScript 提供多種實用類型,以利於常見的類型轉換。這些實用程式可全域使用。
Awaited<Type>
發布:4.5
此類型用於模擬非同步函數中的 `await` 或 `Promise` 上的 `.then()` 方法等運算,特別是它們遞迴解開 `Promise` 的方式。
範例
tsTry
typeA =Awaited <Promise <string>>;typeB =Awaited <Promise <Promise <number>>>;typeC =Awaited <boolean |Promise <number>>;
Partial<Type>
已發布
2.1
建構一個類型,其中 `Type` 的所有屬性都設定為可選。此工具程式會傳回一個類型,代表給定類型的所有子集。
範例
tsTry
interfaceTodo {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
相反。
範例
tsTry
interfaceProps {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
,表示建構型別的屬性無法重新指派。
範例
tsTry
interfaceTodo {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
此公用程式對於表示會在執行階段失敗的指定運算式很有用(例如,嘗試重新指定 凍結物件 的屬性時)。
Object.freeze
ts
function freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys, Type>
已發布
2.1
建構一個物件類型,其屬性金鑰為 Keys
,其屬性值為 Type
。此公用程式可用於將類型的屬性對應到另一個類型。
範例
tsTry
interfaceCatInfo {age : number;breed : string;}typeCatName = "miffy" | "boris" | "mordred";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
(字串文字或字串文字聯集)來建構一個類型。
範例
tsTry
interfaceTodo {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
相反。
範例
tsTry
interfaceTodo {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
的所有聯集成員,來建構類型。
範例
tsTry
typeT0 =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
的所有聯集成員,來建構類型。
範例
tsTry
typeT0 =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
來建構類型。
範例
tsTry
typeT0 =NonNullable <string | number | undefined>;typeT1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
已發布
3.1
從函數類型 Type
的參數中使用的類型建構一個元組類型。
對於重載函式,這將會是最後一個簽章的參數;請參閱 在條件類型中推斷。
範例
tsTry
declare 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
從建構函式類型中類型的類型建立一個元組或陣列類型。它會產生一個包含所有參數類型的元組類型(或類型 never
,如果 Type
不是一個函式)。
範例
tsTry
typeT0 =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
的回傳型別。
對於超載函式,這將會是最後一個簽章的回傳型別;請參閱 在條件型別中推論。
範例
tsTry
declare 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
中建構函式實例的型別。
範例
tsTry
classC {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
ThisParameterType<Type>
已發布
3.3
擷取函式類型的 this 參數類型,如果函式類型沒有 this
參數,則擷取 unknown。
範例
tsTry
functiontoHex (this :Number ) {return this.toString (16);}functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
已發布
3.3
從 Type
中移除 this
參數。如果 Type
沒有明確宣告 this
參數,結果只會是 Type
。否則,會從 Type
建立一個沒有 this
參數的新函式類型。泛型會被清除,而只有最後一個重載簽章會傳播到新的函式類型中。
範例
tsTry
functiontoHex (this :Number ) {return this.toString (16);}constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);console .log (fiveToHex ());
ThisType<Type>
已發布
2.3
此工具程式不會傳回轉換後的類型。相反地,它會作為一個脈絡 this
类型的標記。請注意,必須啟用 noImplicitThis
旗標才能使用此工具程式。
範例
tsTry
typeObjectDescriptor <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 包含一組類型,可用於類型系統中的字串操作。您可以在 模板文字類型 文件中找到這些類型。