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

Iterating and concenating Typescript Types

const defaultThemeColors = {
    primary: [
        "#00000010",
        "#00000020",
        "#00000030",
        "#00000040",
        "#00000050",
        "#00000060",
        "#00000070",
        "#00000080",
        "#00000090",
    ],
    secondary: [
        "#FFFFFF10",
        "#FFFFFF20",
        "#FFFFFF30",
        "#FFFFFF40",
        "#FFFFFF50",
        "#FFFFFF60",
        "#FFFFFF70",
        "#FFFFFF80",
        "#FFFFFF90",
    ]
};
type ColorNums = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";

type ThemeColors = {
    [x in keyof typeof defaultThemeColors]: string;
};
// "primary" | "secondary"

Thats what I was be able to:

type PrimaryType = `primary${ColorNums}`;
// "primary1" | "primary2" | "primary3" | "primary4" | "primary5" | "primary6" | "primary7" | "primary8" | "primary9"

But, I want to iterate theme colors with numbers and expect return like that:

"primary1" | "primary2" | "primary3" | "primary4" | "primary5" | "primary6" | "primary7" | "primary8" | "primary9" | "secondary1" | "secondary2" | "secondary3" | "secondary4" | "secondary5" | "secondary6" | "secondary7" | "secondary8" | "secondary9"

Is there any way to do it? Can it be done using mapped types and template literal types?

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

>Solution :

You’re very close. You just need to do the same thing with the names of the properties as you did with the ColorNums:

type ColorNames = `${keyof typeof defaultThemeColors}${ColorNums}`;

Playground link

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