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?

>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

Leave a Reply