You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1.2KB

  1. import {PromiseValue} from './promise-value';
  2. import {SetReturnType} from './set-return-type';
  3. /**
  4. Create an async version of the given function type, by boxing the return type in `Promise` while keeping the same parameter types.
  5. Use-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.
  6. @example
  7. ```
  8. import {Asyncify} from 'type-fest';
  9. // Synchronous function.
  10. function getFooSync(someArg: SomeType): Foo {
  11. // …
  12. }
  13. type AsyncifiedFooGetter = Asyncify<typeof getFooSync>;
  14. //=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise<Foo>;
  15. // Same as `getFooSync` but asynchronous.
  16. const getFooAsync: AsyncifiedFooGetter = (someArg) => {
  17. // TypeScript now knows that `someArg` is `SomeType` automatically.
  18. // It also knows that this function must return `Promise<Foo>`.
  19. // If you have `@typescript-eslint/promise-function-async` linter rule enabled, it will even report that "Functions that return promises must be async.".
  20. // …
  21. }
  22. ```
  23. */
  24. export type Asyncify<Fn extends (...args: any[]) => any> = SetReturnType<Fn, Promise<PromiseValue<ReturnType<Fn>>>>;