主题
内置高级类型
Parameters
用于提取函数类型的参数类型
typescript
type Parameters<T extends (...args: any) => any>
= T extends (...args: infer P) => any
? P
: never
typescript
type Test = Parameters<(name: string, age: string) => void> // [name: string, age: string]
ReturnType
提取函数类型的返回值类型
typescript
type ReturnType<T extends (...args: any) => any>
= T extends (...args: any) => infer R
? R
: any
typescript
type Test = ReturnType<() => number> // number
ConstructorParameters
提取构造器参数的类型
typescript
type ConstructorParameters<
T extends abstract new (...args: any) => any
> = T extends abstract new (...args: infer P) => any
? P
: never
typescript
interface PersonConstructor {
new(name: string): Person
}
type Test = ConstructorParameters<PersonConstructor> // [name: string]
InstanceType
提取构造器返回值的类型
typescript
type InstanceType<
T extends abstract new (...args: any) => any
> = T extends abstract new (...args: any) => infer R
? R
: any
typescript
interface PersonConstructor {
new(name: string): Person
}
type Test = InstanceType<PersonConstructor> // Person
ThisParameterType
提取 this 的类型
typescript
type ThisParameterType<T> =
T extends (this: infer U, ...args: any[]) => any
? U
: unknown
typescript
type Test = ThisParameterType<(this: Person) => void> // Person
Partial
把索引变为可选
typescript
type Partial<T> = {
[P in keyof T]?: T[P];
}
Required
把索引去掉可选
typescript
type Required<T> = {
[P in keyof T]-?: T[P];
}
Readonly
给索引添加 readonly 修饰
typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
Pick
类型参数 T 为待处理的类型,类型参数 K 为要保留的索引
typescript
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
Omit
类型参数 T 为待处理的类型,类型参数 K 为要去掉的索引
typescript
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
Record
用于创建索引类型,传入 key 和值的类型
typescript
type Record<K extends keyof any, T> = {
[P in K]: T;
}
Exclude
从一个联合类型中去掉一部分类型
typescript
type Exclude<T, U> = T extends U ? never : T
typescript
type Test = Exclude<'a' | 'b' | 'c', 'b' | 'c'> // 'a'
Extract
从一个联合类型中保留一部分类型
typescript
type Extract<T, U> = T extends U ? T : never
typescript
type Test = Exclude<'a' | 'b' | 'c', 'b' | 'c'> // 'b' | 'c'
Awaited
提取 Promise 的 ValuType
typescript
type Awaited<T> =
T extends null | undefined
? T
: T extends object & { then(onfulfilled: infer F): any }
? F extends ((value: infer V, ...args: any) => any)
? Awaited<V>
: never
: T
NonNullable
用于判断是否为非空类型,也就是不是 null 或者 undefined 的类型
typescript
type NonNullable<T> = T extends null | undefined ? never : T
Uppercase、Lowercase、Capitalize、Uncapitalize
大写、小写、首字母大写、去掉首字母大写