Skip to content

Commit

Permalink
Add AsyncReturnType type (#78)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
resynth1943 and sindresorhus committed Feb 14, 2020
1 parent b9b4565 commit ae34d9e
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -16,6 +16,7 @@ export {Opaque} from './source/opaque';
export {SetOptional} from './source/set-optional';
export {SetRequired} from './source/set-required';
export {PromiseValue} from './source/promise-value';
export {AsyncReturnType} from './source/async-return-type';

// Miscellaneous
export {PackageJson} from './source/package-json';
Expand Down
3 changes: 2 additions & 1 deletion readme.md
Expand Up @@ -74,7 +74,8 @@ Click the type names for complete docs.
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise` type.
- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise`.
- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`.

### Miscellaneous

Expand Down
23 changes: 23 additions & 0 deletions source/async-return-type.d.ts
@@ -0,0 +1,23 @@
import {PromiseValue} from './promise-value';

type AsyncFunction = (...args: unknown[]) => Promise<unknown>;

/**
Unwrap the return type of a function that returns a `Promise`.
There has been [discussion](https://github.com/microsoft/TypeScript/pull/35998) about implementing this type in TypeScript.
@example
```ts
import {AsyncReturnType} from 'type-fest';
import {asyncFunction} from 'api';
// This type resolves to the unwrapped return type of `asyncFunction`.
type Value = AsyncReturnType<typeof asyncFunction>;
async function doSomething(value: Value) {}
asyncFunction().then(value => doSomething(value));
```
*/
export type AsyncReturnType<Target extends AsyncFunction> = PromiseValue<ReturnType<Target>>;
13 changes: 13 additions & 0 deletions test-d/async-return-type.ts
@@ -0,0 +1,13 @@
import {expectType, expectError} from 'tsd';
import {AsyncReturnType} from '..';

async function asyncFunction(): Promise<number> {
return Promise.resolve(2);
}

type Value = AsyncReturnType<typeof asyncFunction>;

asyncFunction().then(value => {
expectType<Value>(value);
expectError<string>(value);
});

0 comments on commit ae34d9e

Please sign in to comment.