Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
8 changes: 7 additions & 1 deletion source/promise-value.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ let data: Data = await asyncData;
// Here's an example that shows how this type reacts to non-Promise types.
Comment thread
sindresorhus marked this conversation as resolved.
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<any> ? 0 : 1]
Comment thread
sindresorhus marked this conversation as resolved.
Outdated
: 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