Home > front end >  Map union type into type with argument
Map union type into type with argument

Time:02-01

I have a union type looking like this

type Union = "a"|"b"|"c"

From this type, i want to create a new type that takes each of the possible union values as arguments. Like this:

type NewType = MySpecialType<"a">|MySpecialType<"b">|MySpecialType<"c">

Is there a way to map my Union type into NewType?

I can do this manually but the type I'm working with will potentially grow quite a lot

CodePudding user response:

You can use a self-indexed mapped type:

type Union = "a"|"b"|"c"

type MySpecialType<U extends Union> = { u: U };

type NewType = { [U in Union]:  MySpecialType<U> }[Union];

const a: NewType = { u: 'a' };
const b: NewType = { u: 'b' };
const c: NewType = { u: 'c' };

Playground link

Here, NewType will be resolved as follows:

type NewType = MySpecialType<"a"> | MySpecialType<"b"> | MySpecialType<"c">

CodePudding user response:

Alternative way is to use distributive-conditional-types

type Union = "a" | "b" | "c"

type MySpecialType<U> = { u: U };

type Distribute<T> = T extends any ? MySpecialType<T> : never

type NewType = Distribute<Union>

const a: NewType = { u: 'a' };
const b: NewType = { u: 'b' };
const c: NewType = { u: 'c', };

Playground

  • Related