type-fest
type-fest copied to clipboard
Add a `PromisableFields` type
Facade objects often need to be constructed by pulling data from multiple asynchronous calls. It would be nice if there were a way to create an object that can contain Promisable<>
versions of its fields:
type PromisableFields<ObjectType> = {
[Key in keyof ObjectType]: Promisable<ObjectType[Key]>;
};
interface Foo {
bar: number;
baz: string;
}
type UnresolvedFoo = PromisableFields<Foo>;
/*
This would yield the following type:
{
bar: Promisable<number>;
baz: Promisable<string>;
}
*/
The user would need a function to reconstruct the object after resolving promises, but this would be pretty simple:
export async function resolveFields<ObjectType>(
promisableObject: PromisableFields<ObjectType>
): Promise<ObjectType> {
const partial = {} as Partial<ObjectType>;
for (const [key, promisableValue] of Object.entries(promisableObject)) {
partial[key] = await promisableValue;
}
return partial as ObjectType;
}
If this would be acceptable, I'm happy to create an PR with it and some tests.
Upvote & Fund
- We're using Polar.sh so you can upvote and help fund this issue.
- The funding will be given to active contributors.
- Thank you in advance for helping prioritize & fund our backlog.