diff --git a/index.d.ts b/index.d.ts index 7ade21dfc..34dd2b549 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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'; diff --git a/readme.md b/readme.md index c82ea310f..277a8d040 100644 --- a/readme.md +++ b/readme.md @@ -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 diff --git a/source/async-return-type.d.ts b/source/async-return-type.d.ts new file mode 100644 index 000000000..86d7e717b --- /dev/null +++ b/source/async-return-type.d.ts @@ -0,0 +1,23 @@ +import {PromiseValue} from './promise-value'; + +type AsyncFunction = (...args: unknown[]) => Promise; + +/** +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; + +async function doSomething(value: Value) {} + +asyncFunction().then(value => doSomething(value)); +``` +*/ +export type AsyncReturnType = PromiseValue>; diff --git a/test-d/async-return-type.ts b/test-d/async-return-type.ts new file mode 100644 index 000000000..11555eeaf --- /dev/null +++ b/test-d/async-return-type.ts @@ -0,0 +1,13 @@ +import {expectType, expectError} from 'tsd'; +import {AsyncReturnType} from '..'; + +async function asyncFunction(): Promise { + return Promise.resolve(2); +} + +type Value = AsyncReturnType; + +asyncFunction().then(value => { + expectType(value); + expectError(value); +});