Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AsyncReturnType type #78

Merged
merged 13 commits into from Feb 14, 2020
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
1 change: 1 addition & 0 deletions readme.md
Expand Up @@ -75,6 +75,7 @@ Click the type names for complete docs.
- [`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.
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved
- [`AsyncReturnType`](source/async-return-type.d.ts) - Unpack the return type of a function that returns a `Promise`.
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved

### Miscellaneous

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

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

/**
Unpack the return type of a function that returns a `Promise`.

resynth1943 marked this conversation as resolved.
Show resolved Hide resolved
@example
```ts
import {AsyncReturnType} from 'type-fest';
import {asyncFunction} from 'api';

// This type resolves to the unpacked return type of `asyncFunction`.
type Value = AsyncReturnType<typeof asyncFunction>;

let value: Value = await asyncFunction();
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved
```
*/
export type AsyncReturnType<Target extends AsyncFunction> = PromiseValue<ReturnType<Target>>;
12 changes: 12 additions & 0 deletions test-d/async-return-type.ts
@@ -0,0 +1,12 @@
import {expectType} from 'tsd';
import {AsyncReturnType} from '..';

async function asyncFunction(): Promise<number> {
return Promise.resolve(2);
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved
}

type Value = AsyncReturnType<typeof asyncFunction>;

asyncFunction().then(value => {
expectType<Value>(value);
});
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved