Suppose I have a type like the following:
type Thing = {
aField: string;
anotherField: number;
// ...
}
I would like to make a "mask" type that has all the same fields, but with boolean values:
type ThingMask = {
aField: boolean;
anotherField: boolean;
// ...
}
Is there a way to do this programmatically without having to hardcode the mask type?
Yes, you want a mapped type:
type ThingMask = { [K in keyof Thing]: boolean };
/* type ThingMask = {
aField: boolean;
anotherField: boolean;
} */
Note that by default this will also copy the readonly and optional (?) modifiers from the original type to the mapped type. If you don't want that to happen you cabn alter this behavior by using modifiers like -readonly or -?. But since you didn't ask about that I won't go into it more.
Hope that helps; good luck!
link to code in Playground
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