Your types are not accurate enough and the TypeScript compiler cannot figure it out that they are not promises at that point.
What you need is something like this:
async function promise_props<T>(obj: {[key: string]: Promise<T>}): Promise<{[key: string]: T}> {
const keys = Object.keys(obj);
const awaitables = keys.map(key => obj[key]);
const values = await Promise.all(awaitables);
const result: {[key: string]: T} = {};
keys.forEach((key, i) => {
result[key] = values[i];
});
return result;
}
But it will only work if your object has promises of the same type, for example:
{
company: Promise.resolve("company"),
page: Promise.resolve("1")
};
I'm not sure if it is possible to get it working with various promise types in the current TypeScript version, but as Tao also suggested, you can use the new features in TypeScript 2.8 to get it working:
type UnPromisifiedObject<T> = {[k in keyof T]: UnPromisify<T[k]>}
type UnPromisify<T> = T extends Promise<infer U> ? U : T;
async function promise_props<T extends {[key: string]: Promise<any>}>(obj: T): Promise<UnPromisifiedObject<T>> {
const keys = Object.keys(obj);
const awaitables = keys.map(key => obj[key]);
const values = await Promise.all(awaitables);
const result = {} as any;
keys.forEach((key, i) => {
result[key] = values[i];
});
return result as UnPromisifiedObject<T>;
}
async function main() {
const x = {
company: Promise.resolve("company"),
page: Promise.resolve(1)
};
const res = await promise_props(x);
const company = res.company; // company is a string here
const page = res.page; // page is a number here
}
As you can see, the return type is properly inferred. I think the implementation of the method can be improved. I couldn't find a way to instantiate an instance of the return type and use any
, but although compiler cannot infer it, it's type safe as we resolve all promises.
typescript@next
or wait for TypeScript 2.8 to be released. It will bring conditional types which allows to unwrap a promise type.