Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion source/promise-value.d.ts
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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