File tree 2 files changed +12
-1
lines changed
2 files changed +12
-1
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
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.
3
4
If the type is not a `Promise`, the type itself is returned.
4
5
5
6
@example
@@ -15,6 +16,12 @@ let data: Data = await asyncData;
15
16
// Here's an example that shows how this type reacts to non-Promise types.
16
17
type SyncData = PromiseValue<string>;
17
18
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'));
18
23
```
19
24
*/
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 ;
Original file line number Diff line number Diff line change @@ -2,11 +2,15 @@ import {expectAssignable} from 'tsd';
2
2
import { PromiseValue } from '..' ;
3
3
4
4
type NumberPromise = Promise < number > ;
5
+ type NestedPromise = Promise < NumberPromise > ;
5
6
type Otherwise = object ;
6
7
7
8
// Test the normal behaviour.
8
9
expectAssignable < PromiseValue < NumberPromise > > ( 2 ) ;
9
10
11
+ // Test the nested behaviour.
12
+ expectAssignable < PromiseValue < NestedPromise > > ( 2 ) ;
13
+
10
14
// Test what happens when the `PromiseValue` type is not handed a `Promise` type.
11
15
expectAssignable < PromiseValue < number > > ( 2 ) ;
12
16
You can’t perform that action at this time.
0 commit comments