工具型別

TypeScript 提供了多種工具型別來幫助進行常見的型別轉換。這些工具在全域性範圍內均可使用。

Awaited<Type>

釋出版本: 4.5

此型別旨在模擬 async 函式中的 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

該工具對於表示在執行時會失敗的賦值表示式(例如,嘗試重新賦值 凍結物件 (frozen object) 的屬性)非常有用。

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

Record<Keys, Type>

已釋出
2.1

構造一個物件型別,其屬性鍵為 Keys,屬性值為 Type。此工具可用於將一種型別的屬性對映到另一種型別。

示例
ts
type CatName = "miffy" | "boris" | "mordred";
 
interface CatInfo {
age: number;
breed: string;
}
 
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

從建構函式型別的型別構造一個元組或陣列型別。它產生一個包含所有引數型別的元組型別(如果 Type 不是函式,則為 never 型別)。

示例
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

NoInfer<Type>

已釋出
5.4

阻止對包含的型別進行推斷。除了阻止推斷外,NoInfer<Type>Type 完全相同。

示例
ts
function createStreetLight<C extends string>(
colors: C[],
defaultColor?: NoInfer<C>,
) {
// ...
}
createStreetLight(["red", "yellow", "green"], "red"); // OK
createStreetLight(["red", "yellow", "green"], "blue"); // Error

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)
HXHong Xu (2)
34+

最後更新:2026 年 3 月 27 日