Skip to content

Commit 577c2a2

Browse files
onichandamesindresorhus
andauthoredJun 27, 2020
Make the PromiseValue type handle nested promises (#112)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
1 parent 493d9d4 commit 577c2a2

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed
 

‎source/promise-value.d.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/**
22
Returns the type that is wrapped inside a `Promise` type.
3+
If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained.
34
If the type is not a `Promise`, the type itself is returned.
45
56
@example
@@ -15,6 +16,12 @@ let data: Data = await asyncData;
1516
// Here's an example that shows how this type reacts to non-Promise types.
1617
type SyncData = PromiseValue<string>;
1718
let syncData: SyncData = getSyncData();
19+
20+
// Here's an example that shows how this type reacts to recursive Promise types.
21+
type RecursiveAsyncData = Promise<Promise<string> >;
22+
let recursiveAsyncData: PromiseValue<RecursiveAsyncData> = Promise.resolve(Promise.resolve('ABC'));
1823
```
1924
*/
20-
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value> ? Value : Otherwise;
25+
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value>
26+
? { 0: PromiseValue<Value>; 1: Value }[PromiseType extends Promise<unknown> ? 0 : 1]
27+
: Otherwise;

‎test-d/promise-value.ts

+4
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ import {expectAssignable} from 'tsd';
22
import {PromiseValue} from '..';
33

44
type NumberPromise = Promise<number>;
5+
type NestedPromise = Promise<NumberPromise>;
56
type Otherwise = object;
67

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

11+
// Test the nested behaviour.
12+
expectAssignable<PromiseValue<NestedPromise>>(2);
13+
1014
// Test what happens when the `PromiseValue` type is not handed a `Promise` type.
1115
expectAssignable<PromiseValue<number>>(2);
1216

0 commit comments

Comments
 (0)
Please sign in to comment.