假设我有一个这样的物体:
export const v = {
a() : Promise<X>{
},
b() : Promise<Y>{
},
c() : Promise<Z>{
}
}我的问题是-有什么方法可以得到v的类型,但是要映射类型,这样它看起来就像这样:
export type V = {
a: X,
b: Y,
c: Z
}基本上,我在映射对象中的每个键,到相应承诺的解析值。
基本上,我试图从静态声明的内容中派生出一个修改的类型。
发布于 2018-05-09 07:42:49
您可以使用条件类型和映射类型来完成此操作:
class X{}
class Y{}
class Z{}
export const v = {
a() : Promise<X>{
return null as any;
},
b() : Promise<Y>{
return null as any;
},
c() : Promise<Z>{
return null as any;
},
}
type ExtractAllPromisses<T> =
{
// Take all keys of T ([P in keyof T])
// and if the property P of T is a promise returning function (T[P] extends ()=> Promise<infer U>)
// then the new type of P will be the return type of the promise (saved in U)
// Otherwise the new type of P is never
[P in keyof T]: T[P] extends ()=> Promise<infer U> ? U : never
};
export type V = ExtractAllPromisses<typeof v> // same as type V = { a: X; b: Y; c: Z; }您可以根据需要在条件类型中执行一些变化,上面的示例特别适用于只具有不带参数并返回Promise的函数的类型。
如果要将函数与任意数量的参数匹配,可以使用:
type ExtractAllPromisses<T> = { [P in keyof T]: T[P] extends (...args: any[])=> Promise<infer U> ? U : never };如果您的类型还有一些属性不能保证返回函数,并且希望保留这些属性(即v也有一个字段foo:number),则可以使用:
type ExtractAllPromisses<T> = { [P in keyof T]: T[P] extends (...args: any[])=> Promise<infer U> ? U : T[P] };如果您想要排除那些不是允诺重调函数的属性。你可以过滤钥匙:
type PromiseFunctionFields<T> = { [P in keyof T] : T[P] extends (...args: any[])=> Promise<any> ? P : never}[keyof T];
type ExtractAllPromisses<T> = { [P in PromiseFunctionFields<T>]: T[P] extends (...args: any[])=> Promise<infer U> ? U : T[P] };https://stackoverflow.com/questions/50247785
复制相似问题