How would you write a mapped type that converts every method on an interface into a Promise-returning async version, for a mock or proxy implementation?
Short answer
Use a conditional type inside the mapped type to detect function-typed properties specifically, and for those, produce a new function type with the same parameters but a Promise-wrapped return type — leaving non-function properties unchanged (or omitted, depending on the use…
Advertisement
AModel answer
Use a conditional type inside the mapped type to detect function-typed properties specifically, and for those, produce a new function type with the same parameters but a Promise-wrapped return type — leaving non-function properties unchanged (or omitted, depending on the use case).
type Asyncify<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer R
? (...args: A) => Promise<R>
: T[K]
};
interface Api { getUser(id: string): User; }
type AsyncApi = Asyncify<Api>;
// { getUser(id: string): Promise<User> }Real-world example
Generating a fully-typed async mock or remote-proxy version of a synchronous service interface automatically.
Likely follow-ups
- How would you handle methods that ALREADY return a Promise, to avoid double-wrapping (Promise<Promise<T>>)?
Related topics