From 7fe70fd821e67a1273c5beea227bca3a677dd8be Mon Sep 17 00:00:00 2001 From: Resynth <49915996+resynth1943@users.noreply.github.com> Date: Thu, 6 Feb 2020 20:24:28 +0000 Subject: [PATCH] Add `PromiseValue` type (#75) Co-authored-by: Sindre Sorhus --- index.d.ts | 1 + readme.md | 1 + source/promise-value.d.ts | 20 ++++++++++++++++++++ test-d/promise-value.ts | 14 ++++++++++++++ 4 files changed, 36 insertions(+) create mode 100644 source/promise-value.d.ts create mode 100644 test-d/promise-value.ts diff --git a/index.d.ts b/index.d.ts index d611efb9f..7ade21dfc 100644 --- a/index.d.ts +++ b/index.d.ts @@ -15,6 +15,7 @@ export {Promisable} from './source/promisable'; export {Opaque} from './source/opaque'; export {SetOptional} from './source/set-optional'; export {SetRequired} from './source/set-required'; +export {PromiseValue} from './source/promise-value'; // Miscellaneous export {PackageJson} from './source/package-json'; diff --git a/readme.md b/readme.md index fd8907a1c..c82ea310f 100644 --- a/readme.md +++ b/readme.md @@ -74,6 +74,7 @@ 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. ### Miscellaneous diff --git a/source/promise-value.d.ts b/source/promise-value.d.ts new file mode 100644 index 000000000..7686dd11d --- /dev/null +++ b/source/promise-value.d.ts @@ -0,0 +1,20 @@ +/** +Returns the type that is wrapped inside a `Promise` type. +If the type is not a `Promise`, the type itself is returned. + +@example +``` +import {PromiseValue} from 'type-fest'; + +type AsyncData = Promise; +let asyncData: PromiseValue = Promise.resolve('ABC'); + +type Data = PromiseValue; +let data: Data = await asyncData; + +// Here's an example that shows how this type reacts to non-Promise types. +type SyncData = PromiseValue; +let syncData: SyncData = getSyncData(); +``` +*/ +export type PromiseValue = PromiseType extends Promise ? Value : Otherwise; diff --git a/test-d/promise-value.ts b/test-d/promise-value.ts new file mode 100644 index 000000000..d055c6c7e --- /dev/null +++ b/test-d/promise-value.ts @@ -0,0 +1,14 @@ +import {expectType} from 'tsd'; +import {PromiseValue} from '..'; + +type NumberPromise = Promise; +type Otherwise = object; + +// Test the normal behaviour. +expectType>(2); + +// Test what happens when the `PromiseValue` type is not handed a `Promise` type. +expectType>(2); + +// Test the `Otherwise` generic parameter. +expectType>({});