Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the PromiseValue type handle nested promises #112

Merged
merged 9 commits into from Jun 27, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion source/promise-value.d.ts
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.
sindresorhus marked this conversation as resolved.
Show resolved Hide 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]
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
: 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