Chris Talman
Chris Talman

Reputation: 1169

Get Generic Type from Type

Can the generic type be retrieved from a Promise type?

For instance, the following type:

type Example = Promise<boolean>;

Is it possible to extract the generic type, boolean, into its own type? For instance:

type BooleanPromise = Promise<boolean>;
type Value = genericsof Example[0]; // boolean

Thanks for any help.

Upvotes: 1

Views: 115

Answers (2)

bluelovers
bluelovers

Reputation: 1255

a, a2 is boolean

import { ITSResolvable, ITSUnpacked } from 'ts-type';

export type Example = Promise<boolean>;

export type ValueTypeOfExample = ITSUnpacked<Example>;

let a: ValueTypeOfExample;

a = true;

// @ts-ignore err when without @ts-ignore
a = 0;
// @ts-ignore err when without @ts-ignore
a = '';

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You can use a conditional type to extract the generic type argument from a generic type instantiation:

type Example = Promise<boolean>;

type BooleanPromise = Promise<boolean>;
type Value = BooleanPromise extends Promise<infer V> ? V : never // boolean

You can even create a generic type that extracts the argument from any promise instantiation:

type PromiseValue<T> = T extends Promise<infer V> ? V : never 
type Value2 = PromiseValue<BooleanPromise>

You can read more about conditional types here

Upvotes: 2

Related Questions