Discover the Magic of Mapped Types with this simple example:
type X = 'red' | 'blue' | 'green';
type Y = {
[item in X]: boolean;
};
Y
results in:
{
red: boolean;
blue: boolean;
green: boolean;
}
Explore More!
And don't forget, as Aleksey L. suggests, there's a handy utility type called Record
:
type Y = Record<X, boolean>;
With mapped types, you can even vary the property types using conditional types:
type X = 'red' | 'blue' | 'green';
type Y = {
[item in X]: item extends 'red' ? number : boolean;
};
Y
transforms into:
{
red: number;
blue: boolean;
green: boolean;
}
Don't Miss Out on Trying It Yourself!