實用程式類型

TypeScript 提供多種實用類型,以利於常見的類型轉換。這些實用程式可全域使用。

Awaited<Type>

發布:4.5

此類型用於模擬非同步函數中的 `await` 或 `Promise` 上的 `.then()` 方法等運算,特別是它們遞迴解開 `Promise` 的方式。

範例
ts
type A = Awaited<Promise<string>>;
type A = string
 
type B = Awaited<Promise<Promise<number>>>;
type B = number
 
type C = Awaited<boolean | Promise<number>>;
type C = number | boolean
Try

Partial<Type>

已發布
2.1

建構一個類型,其中 `Type` 的所有屬性都設定為可選。此工具程式會傳回一個類型,代表給定類型的所有子集。

範例
ts
interface Todo {
title: string;
description: string;
}
 
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
 
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
 
const todo2 = updateTodo(todo1, {
description: "throw out trash",
});
Try

Required<Type>

已發布
2.8

建構一個型別,包含 Type 的所有屬性,設定為必填。與 Partial 相反。

範例
ts
interface Props {
a?: number;
b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 };
Property '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>'.
Try

Readonly<Type>

已發布
2.1

建構一個型別,包含 Type 的所有屬性,設定為 readonly,表示建構型別的屬性無法重新指派。

範例
ts
interface Todo {
title: string;
}
 
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
 
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.
Try

此公用程式對於表示會在執行階段失敗的指定運算式很有用(例如,嘗試重新指定 凍結物件 的屬性時)。

Object.freeze
ts
function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys, Type>

已發布
2.1

建構一個物件類型,其屬性金鑰為 Keys,其屬性值為 Type。此公用程式可用於將類型的屬性對應到另一個類型。

範例
ts
interface CatInfo {
age: number;
breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
 
cats.boris;
const cats: Record<CatName, CatInfo>
Try

Pick<Type, Keys>

已發布
2.1

Type 中挑選一組屬性 Keys(字串文字或字串文字聯集)來建構一個類型。

範例
ts
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
 
todo;
const todo: TodoPreview
Try

Omit<Type, Keys>

已發布
3.5

透過從 Type 選取所有屬性,然後移除 Keys(字串文字或字串文字聯集),來建構類型。與 Pick 相反。

範例
ts
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
 
todo;
const todo: TodoPreview
 
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
 
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
 
todoInfo;
const todoInfo: TodoInfo
Try

Exclude<UnionType, ExcludedMembers>

已發布
2.8

UnionType 中排除可指定給 ExcludedMembers 的所有聯集成員,來建構類型。

範例
ts
type T0 = Exclude<"a" | "b" | "c", "a">;
type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
type T2 = string | number
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T3 = Exclude<Shape, { kind: "circle" }>
type T3 = { kind: "square"; x: number; } | { kind: "triangle"; x: number; y: number; }
Try

Extract<Type, Union>

已發布
2.8

Type 中萃取可指定給 Union 的所有聯集成員,來建構類型。

範例
ts
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
type T1 = () => void
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T2 = Extract<Shape, { kind: "circle" }>
type T2 = { kind: "circle"; radius: number; }
Try

NonNullable<Type>

已發布
2.8

透過從 Type 排除 nullundefined 來建構類型。

範例
ts
type T0 = NonNullable<string | number | undefined>;
type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
type T1 = string[]
Try

Parameters<Type>

已發布
3.1

從函數類型 Type 的參數中使用的類型建構一個元組類型。

對於重載函式,這將會是最後一個簽章的參數;請參閱 在條件類型中推斷

範例
ts
declare function f1(arg: { a: number; b: string }): void;
 
type T0 = Parameters<() => string>;
type T0 = []
type T1 = Parameters<(s: string) => void>;
type T1 = [s: string]
type T2 = Parameters<<T>(arg: T) => T>;
type T2 = [arg: unknown]
type T3 = Parameters<typeof f1>;
type T3 = [arg: { a: number; b: string; }]
type T4 = Parameters<any>;
type T4 = unknown[]
type T5 = Parameters<never>;
type T5 = never
type T6 = Parameters<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T6 = never
type T7 = Parameters<Function>;
Type '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'.
type T7 = never
Try

ConstructorParameters<Type>

已發布
3.1

從建構函式類型中類型的類型建立一個元組或陣列類型。它會產生一個包含所有參數類型的元組類型(或類型 never,如果 Type 不是一個函式)。

範例
ts
type T0 = ConstructorParameters<ErrorConstructor>;
type T0 = [message?: string]
type T1 = ConstructorParameters<FunctionConstructor>;
type T1 = string[]
type T2 = ConstructorParameters<RegExpConstructor>;
type T2 = [pattern: string | RegExp, flags?: string]
class C {
constructor(a: number, b: string) {}
}
type T3 = ConstructorParameters<typeof C>;
type T3 = [a: number, b: string]
type T4 = ConstructorParameters<any>;
type T4 = unknown[]
 
type T5 = ConstructorParameters<Function>;
Type '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'.
type T5 = never
Try

ReturnType<Type>

已發布
2.8

建構一個型別,包含函式 Type 的回傳型別。

對於超載函式,這將會是最後一個簽章的回傳型別;請參閱 在條件型別中推論

範例
ts
declare function f1(): { a: number; b: string };
 
type T0 = ReturnType<() => string>;
type T0 = string
type T1 = ReturnType<(s: string) => void>;
type T1 = void
type T2 = ReturnType<<T>() => T>;
type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T3 = number[]
type T4 = ReturnType<typeof f1>;
type T4 = { a: number; b: string; }
type T5 = ReturnType<any>;
type T5 = any
type T6 = ReturnType<never>;
type T6 = never
type T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type T8 = ReturnType<Function>;
Type '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'.
type T8 = any
Try

InstanceType<Type>

已發布
2.8

建構一個型別,包含 Type 中建構函式實例的型別。

範例
ts
class C {
x = 0;
y = 0;
}
 
type T0 = InstanceType<typeof C>;
type T0 = C
type T1 = InstanceType<any>;
type T1 = any
type T2 = InstanceType<never>;
type T2 = never
type T3 = InstanceType<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<Function>;
Type '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'.
type T4 = any
Try

ThisParameterType<Type>

已發布
3.3

擷取函式類型的 this 參數類型,如果函式類型沒有 this 參數,則擷取 unknown

範例
ts
function toHex(this: Number) {
return this.toString(16);
}
 
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
Try

OmitThisParameter<Type>

已發布
3.3

Type 中移除 this 參數。如果 Type 沒有明確宣告 this 參數,結果只會是 Type。否則,會從 Type 建立一個沒有 this 參數的新函式類型。泛型會被清除,而只有最後一個重載簽章會傳播到新的函式類型中。

範例
ts
function toHex(this: Number) {
return this.toString(16);
}
 
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
 
console.log(fiveToHex());
Try

ThisType<Type>

已發布
2.3

此工具程式不會傳回轉換後的類型。相反地,它會作為一個脈絡 this 类型的標記。請注意,必須啟用 noImplicitThis 旗標才能使用此工具程式。

範例
ts
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};
 
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
let data: object = desc.data || {};
let methods: object = desc.methods || {};
return { ...data, ...methods } as D & M;
}
 
let obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // Strongly typed this
this.y += dy; // Strongly typed this
},
},
});
 
obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);
Try

在上面的範例中,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 包含一組類型,可用於類型系統中的字串操作。您可以在 模板文字類型 文件中找到這些類型。

TypeScript 文件是一個開源專案。歡迎透過 傳送 Pull Request 協助我們改善這些頁面 ❤

此頁面的貢獻者
Cchristian (54)
OTOrta Therox (23)
Bbob1983 (4)
JBJack Bates (3)
JJetLu (2)
32+

最後更新:2024 年 3 月 21 日