目录
类型推导: inference, 使用 infer 关键字
只能用在条件类型中,用来
提取类型的某一个部分的类型
,放在不同的位置 就可以取不同位置的类型ReturnType
,Parameters
,InstanceType
,ConstructorParameters
内置的类型
1.ReturnType 返回值类型
function getUser(name: string, age: number) {
return { name, age, address: {} };
}
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type T1 = ReturnType<typeof getUser>; // 泛型需要传递类型,所以使用 typeof
2.Parameters 参数类型
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
type T2 = Parameters<typeof getUser>;
3.InstanceType 实例类型
class Person {
constructor() {
return { a: 1, b: 2 };
}
} // Person的实例类型是什么? Person
type InstanceType<T extends new (...args: any[]) => any> = T extends { new (...args: any[]): infer I } ? I : never;
type T3 = InstanceType<typeof Person>; // 内置的
type T4 = Person;
4.ConstructorParameters 构造函数参数类型
class Person {
constructor() {
return { a: 1, b: 2 };
}
}
type ConstructorParameters<T extends new (...args: any[]) => any> = T extends new (...args: infer P) => any ? P : never;
type T5 = ConstructorParameters<typeof Person>;
5.infer 实践
``
更改元组类型
type TailToHead<T extends any[]> = T extends [...infer C, infer B] ? [B, ...C] : any;
type x = TailToHead<["Echoyya", 30, 40, 50, "beijing"]>; // ["beijing","Echoyya",30,40,50]
将元组转换成联合类型
写法一:类型单一时,可返回正确类型,元组类型时,不好判断 暂返回 字符串 "R" 进行验证
type ElementOf<T> = T extends Array<string | number | boolean> ? "R" : any; // (string|number|boolean)[]
// 写法二: 由写法一演变而来 infer R
type ElementOf<T> = T extends Array<infer R> ? R : any;
type TupleToUnion = ElementOf<[string, number, boolean]>; // 返回联合类型 string | number | boolean
获取 Promise 返回值类型(递归)
type PromiseV<T> = T extends Promise<infer V> ? PromiseV<V> : T;
type PromiseReturnValue = PromiseV<Promise<number>>; // number
type PromiseReturnValue2 = PromiseV<Promise<Promise<string>>>; // string
标签:...,TypeScript,any,extends,类型,type,infer
From: https://www.cnblogs.com/echoyya/p/17189296.html