Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Defining multiple mapped types in typescript?

Say I have the following typescript code:

type fruit = "apple" | "banana" | "pear"
type color = "red" | "yellow" | "green"

And I want to create a type that has a numeric property for each fruit and a boolean property for each color, something like

type FruitsAndColors = {
  [key in fruit]: number;
  [key in color]: boolean
}

Unfortunately, this errors with the message "A mapped type may not declare properties or methods", yet it compiles fine. What’s actually happening here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can get around this with something like

type FruitsAndColors = {
  [key in fruit]: number;
} & {
  [key in color]: boolean
}

But I’d like to know what the actual issue is.

>Solution :

It’s not "vscode’s typescript extension," it’s TypeScript. It doesn’t let you do two mappings in a single type construct. It’s just the syntax of the construct doesn’t allow it.

Instead, you do what you showed:

type FruitsAndColors = {
    [key in fruit]: number;
} & {
    [key in color]: boolean
};

Note, though, that that type requires all six properties to be present in the object. Maybe that’s what you want, but if not, add ? after the mapped keys (or wrap the entire thing in Partial<>):

type FruitsAndColors = {
    [key in fruit]?: number;
} & {
    [key in color]?: boolean
};
// Or
type FruitsAndColors = Partial<{
    [key in fruit]: number;
} & {
    [key in color]: boolean
}>;

Playground for the above

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading