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

Add PromiseValue type #75

Merged
merged 6 commits into from Feb 6, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -15,6 +15,7 @@ export {Promisable} from './source/promisable';
export {Opaque} from './source/opaque';
export {SetOptional} from './source/set-optional';
export {SetRequired} from './source/set-required';
export {PromiseValue} from './source/promise-value';

// Miscellaneous
export {PackageJson} from './source/package-json';
1 change: 1 addition & 0 deletions readme.md
Expand Up @@ -74,6 +74,7 @@ Click the type names for complete docs.
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise` type.

### Miscellaneous

Expand Down
18 changes: 18 additions & 0 deletions source/promise-value.d.ts
@@ -0,0 +1,18 @@
/**
Returns the type that is wrapped inside a `Promise` type.
If the type is not a `Promise`, the type itself is returned.

@example
import {PromiseValue} from './promise-value';

type AsyncData = Promise<string>;
let asyncData: PromiseValue<AsyncData> = Promise.resolve('ABC');

type Data = PromiseValue<AsyncData>;
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();
*/
export type PromiseValue<PromiseType, Otherwise = PromiseType> = PromiseType extends Promise<infer Value> ? Value : Otherwise;
14 changes: 14 additions & 0 deletions test-d/promise-value.ts
@@ -0,0 +1,14 @@
import {expectType} from 'tsd';
import {PromiseValue} from '..';

type NumberPromise = Promise<number>;
type Otherwise = object;

// Test the normal behaviour.
expectType<PromiseValue<NumberPromise>>(2);

// Test what happens when the `PromiseValue` type is not handed a `Promise` type.
expectType<PromiseValue<number>>(2);

// Test the `Otherwise` generic parameter.
expectType<PromiseValue<number, Otherwise>>({});