Is this possible in Typescript?
I want to turn e.g. something like this:
JavaScript
x
5
1
interface IPromiseObject {
2
promiseA: Promise<number>;
3
promiseB: Promise<string>;
4
}
5
Into this:
JavaScript
1
5
1
interface IResolvedPromiseObject {
2
promiseA: number;
3
promiseB: string;
4
}
5
I want to use it to resolve an object with promises as values, but still stay type safe. In this example, I need to convert IPromiseObject
to an object with the same keys but the values resolved so that I can use it as return type.
JavaScript
1
9
1
export async function resolveAllObject<IPromiseObject>( promiseObject: IPromiseObject ): Promise<???> {
2
const resolvedPromiseObject = {};
3
for ( const key in promiseObject ) {
4
const value = await promiseObject[ key ];
5
Object.assign( resolvedPromiseObject, { [ key ]: value } );
6
}
7
return resolvedPromiseObject;
8
}
9
Advertisement
Answer
You can map over the properties and use the Awaited
utility type to extract the type inside the Promise.
JavaScript
1
4
1
type AwaitedObject<T> = {
2
[K in keyof T]: Awaited<T[K]>
3
}
4
Usage:
JavaScript
1
15
15
1
interface IPromiseObject {
2
promiseA: Promise<number>;
3
promiseB: Promise<string>;
4
}
5
6
type AwaitedObject<T> = {
7
[K in keyof T]: Awaited<T[K]>
8
}
9
10
type IResolvedPromiseObject = AwaitedObject<IPromiseObject>
11
// type IResolvedPromiseObject = {
12
// promiseA: number;
13
// promiseB: string;
14
// }
15