Skip to content
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待

实用类型

TypeScript 提供了几种实用类型来促进常见的类型转换。这些工具类型是全局可用的。

Awaited<Type>

发布版本: 4.5

此类型用于建模 async 函数中的 await 操作,或者 Promise 上的 .then() 方法——具体来说,就是它们递归地展开 Promise 的方式。

示例
ts
type 
A
=
Awaited
<
Promise
<string>>;
type
B
=
Awaited
<
Promise
<
Promise
<number>>>;
type
C
=
Awaited
<boolean |
Promise
<number>>;
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>'.
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.
Try

此工具对于表示将在运行时失败的赋值表达式很有用(例如,当尝试重新分配冻结对象的属性时)。

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
;
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
;
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
;
type
TodoInfo
=
Omit
<Todo, "completed" | "createdAt">;
const
todoInfo
:
TodoInfo
= {
title
: "Pick up kids",
description
: "Kindergarten closes at 5pm",
};
todoInfo
;
Try

Exclude<UnionType, ExcludedMembers>

发布版本:
2.8

通过从 UnionType 中排除所有可赋值给 ExcludedMembers 的联合成员来构造一个类型。

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

Extract<Type, Union>

发布版本:
2.8

通过从 Type 中提取所有可赋值给 Union 的联合成员来构造一个类型。

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

NonNullable<Type>

发布版本:
2.8

通过从 Type 中排除 nullundefined 来构造一个类型。

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

Parameters<Type>

发布版本:
3.1

从函数类型 Type 的参数所用类型构造一个元组类型。

对于重载函数,这将是最后一个签名的参数;请参阅在条件类型中推断

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

ConstructorParameters<Type>

发布版本:
3.1

从构造函数类型的类型构造一个元组或数组类型。它生成一个包含所有参数类型的元组类型(如果 Type 不是函数,则生成类型 never)。

示例
ts
type 
T0
=
ConstructorParameters
<ErrorConstructor>;
type
T1
=
ConstructorParameters
<FunctionConstructor>;
type
T2
=
ConstructorParameters
<RegExpConstructor>;
class
C
{
constructor(
a
: number,
b
: string) {}
} type
T3
=
ConstructorParameters
<typeof
C
>;
type
T4
=
ConstructorParameters
<any>;
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'.
Try

ReturnType<Type>

发布版本:
2.8

构造一个由函数 Type 的返回类型组成的类型。

对于重载函数,这将是最后一个签名的返回类型;请参阅在条件类型中推断

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

InstanceType<Type>

发布版本:
2.8

构造一个由 Type 中构造函数类型的实例类型组成的类型。

示例
ts
class 
C
{
x
= 0;
y
= 0;
} type
T0
=
InstanceType
<typeof
C
>;
type
T1
=
InstanceType
<any>;
type
T2
=
InstanceType
<never>;
type
T3
=
InstanceType
<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => 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'.
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
>; // 方法中 'this' 的类型是 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
; // 强类型 this
this.
y
+=
dy
; // 强类型 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 包含了一组可以在类型系统内用于字符串操作的类型。你可以在模板字面量类型文档中找到它们。