Skip to content

Commit

Permalink
Add PromiseValue type (#75)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
resynth1943 and sindresorhus authored Feb 6, 2020
1 parent 8b857ce commit 7fe70fd
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 20 additions & 0 deletions source/promise-value.d.ts
Original file line number Diff line number Diff line change
@@ -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<string>;
let asyncData: PromiseValue<AsyncData> = Promise.resolve('ABC');
type Data = PromiseValue<AsyncData>;
let data: Data = await asyncData;
// Here's an example that shows how this type reacts to non-Promise types.
type SyncData = PromiseValue<string>;
let syncData: SyncData = getSyncData();
```
*/
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value> ? Value : Otherwise;
14 changes: 14 additions & 0 deletions test-d/promise-value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {expectType} from 'tsd';
import {PromiseValue} from '..';

type NumberPromise = Promise<number>;
type Otherwise = object;

// Test the normal behaviour.
expectType<PromiseValue<NumberPromise>>(2);

// Test what happens when the `PromiseValue` type is not handed a `Promise` type.
expectType<PromiseValue<number>>(2);

// Test the `Otherwise` generic parameter.
expectType<PromiseValue<number, Otherwise>>({});

0 comments on commit 7fe70fd

Please sign in to comment.