I am currently working on developing a custom typed Promise.props(...) utility function that dynamically assigns correct types based on the input object.
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;
}, {});
}
At this point, I have defined the type T
as the input parameter and also specified U
, which has identical keys but different value types.
I am wondering if it is possible to determine the result type from a Promise in the same way that I can extract the keys of an input parameter.
When using this function, the process should resemble the following example:
const result = await this.props({
val1: Promise.resolve('test'),
val2: Promise.resolve(123),
val3: ['a', 'b', 'c']
});
As a result, the IDE should be able to infer that:
result.val1 is a string
result.val2 is a number
result.val3 is an array