Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map union to interface properties

Tags:

typescript

Is it possible to map a union type to interface in Typescript?

What I'd Like to be able to do

Given a union type A:

type A = 'one' | 'two' | 'three';

I'd like to be able to map it to interface B:

interface B {
    one:   boolean;
    two:   boolean;
    three: boolean;
}
like image 700
ElSajko Avatar asked Mar 16 '26 21:03

ElSajko


1 Answers

Mapped Types make this surprisingly easy:

type A = 'one' | 'two' | 'three';

type B = {
    [property in A]: boolean;
};

B ends up being:

{
    one:   boolean;
    two:   boolean;
    three: boolean;
}

Playground link

But as Aleksey L. points out, there's a utility type for that: Record:

type B = Record<A, boolean>;

With mapped types, you can even make the types of the properties different by throwing conditional types into the mix:

type A = 'one' | 'two' | 'three';

type B = {
    [property in A]: property extends 'one' ? number : boolean;
};

B ends up being:

{
    one:   number;
    two:   boolean;
    three: boolean;
}

Playground link

like image 148
T.J. Crowder Avatar answered Mar 19 '26 13:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!