我想创建一个类型化的Promise.props(...)实用程序函数,它根据输入对象返回正确的类型。
static async props<T extends {[key: string]: Promise<S>|S}, S, U extends { [key in keyof T]: S}>(obj: T): Promise<U> {
const promises = [];
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
promises.push(obj[key]);
}
const results = await Promise.all(promises);
return results.reduce((map, current, index) => {
map[keys[index]] = current;
return map;
}, {});
}
到目前为止,我得到的是T
类型,它是输入参数。我还定义了U
,它具有相同的键但应该具有不同的值类型。
是否可以从Promise获取结果类型,并且我可以获取输入参数的键。
使用该功能应该如下所示:
const result = await this.props({
val1: Promise.resolve('test'),
val2: Promise.resolve(123),
val3: ['a', 'b', 'c']
});
IDE应该知道:
result.val1 is a string
result.val2 is a number
result.val3 is an array
答案 0 :(得分:2)
我认为这应该有效:
static async props<T>(obj: {[K in keyof T]: Promise<T[K]> | T[K]}): Promise<T> {
// (I didn't look at the implementation)
}