Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type for with same field names but different types

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?

like image 810
Bluefire Avatar asked Nov 24 '25 10:11

Bluefire


1 Answers

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

like image 84
jcalz Avatar answered Nov 26 '25 22:11

jcalz



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!