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
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.

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 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);
});
resynth1943 marked this conversation as resolved.
Show resolved Hide resolved