UNPKG

1.22 kBTypeScriptView Raw
1import type {SetReturnType} from './set-return-type';
2
3/**
4Create an async version of the given function type, by boxing the return type in `Promise` while keeping the same parameter types.
5
6Use-case: You have two functions, one synchronous and one asynchronous that do the same thing. Instead of having to duplicate the type definition, you can use `Asyncify` to reuse the synchronous type.
7
8@example
9```
10import type {Asyncify} from 'type-fest';
11
12// Synchronous function.
13function getFooSync(someArg: SomeType): Foo {
14 // …
15}
16
17type AsyncifiedFooGetter = Asyncify<typeof getFooSync>;
18//=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise<Foo>;
19
20// Same as `getFooSync` but asynchronous.
21const getFooAsync: AsyncifiedFooGetter = (someArg) => {
22 // TypeScript now knows that `someArg` is `SomeType` automatically.
23 // It also knows that this function must return `Promise<Foo>`.
24 // If you have `@typescript-eslint/promise-function-async` linter rule enabled, it will even report that "Functions that return promises must be async.".
25
26 // …
27}
28```
29
30@category Async
31*/
32export type Asyncify<Function_ extends (...arguments_: any[]) => any> = SetReturnType<Function_, Promise<Awaited<ReturnType<Function_>>>>;