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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With