Skip to content

Commit

Permalink
Make the PromiseValue type handle nested promises (#112)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
onichandame and sindresorhus committed Jun 27, 2020
1 parent 493d9d4 commit 577c2a2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
9 changes: 8 additions & 1 deletion source/promise-value.d.ts
@@ -1,5 +1,6 @@
/**
Returns the type that is wrapped inside a `Promise` type.
If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained.
If the type is not a `Promise`, the type itself is returned.
@example
Expand All @@ -15,6 +16,12 @@ 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();
// Here's an example that shows how this type reacts to recursive Promise types.
type RecursiveAsyncData = Promise<Promise<string> >;
let recursiveAsyncData: PromiseValue<RecursiveAsyncData> = Promise.resolve(Promise.resolve('ABC'));
```
*/
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value> ? Value : Otherwise;
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value>
? { 0: PromiseValue<Value>; 1: Value }[PromiseType extends Promise<unknown> ? 0 : 1]
: Otherwise;
4 changes: 4 additions & 0 deletions test-d/promise-value.ts
Expand Up @@ -2,11 +2,15 @@ import {expectAssignable} from 'tsd';
import {PromiseValue} from '..';

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

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

// Test the nested behaviour.
expectAssignable<PromiseValue<NestedPromise>>(2);

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

Expand Down

0 comments on commit 577c2a2

Please sign in to comment.