Home > Net >  Extract constraint from generic type
Extract constraint from generic type

Time:09-25

Given the following generic type:

interface SomeWrapper<TValue extends string | number | boolean | null = string> {
  // ...
}

Is there any way for me to extract the constraint into a type?

type SomeConstraint = DoSomeMagicHere<SomeWrapper> // = string | number | boolean | null

CodePudding user response:

I'm not sure what the use of it is, but you can extract it like this:

interface SomeWrapper<
  TValue extends string | number | boolean | null = string
> {
  // ...
}

type SomeConstraint = any extends SomeWrapper<infer R> ? R : never;
// = string | number | boolean | null
  • Related