使用 Typescript 将泛型类型添加到 Promise.props(...)
Add generic types to Promise.props(...) with Typescript
我想创建一个类型化的 Promise.props(...) 实用函数,它 returns 根据输入对象正确类型化。
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
我认为这应该可行:
static async props<T>(obj: {[K in keyof T]: Promise<T[K]> | T[K]}): Promise<T> {
// (I didn't look at the implementation)
}
我想创建一个类型化的 Promise.props(...) 实用函数,它 returns 根据输入对象正确类型化。
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
我认为这应该可行:
static async props<T>(obj: {[K in keyof T]: Promise<T[K]> | T[K]}): Promise<T> {
// (I didn't look at the implementation)
}