Home > Blockchain >  How to "cross-product" types in typescript?
How to "cross-product" types in typescript?

Time:09-26

I want to "cross-product" two types.

What I mean by 'cross-product of types' is, example I have 2 types,

type color = "red" | "green";

and

type shade = "100" | "200" | "300";

I want to get a final type which accepts these string values only

"red.100"
"red.200"
"red.300"
"green.100"
"green.200"
"green.300"

I know I can do this...

type colorShade = "red.100" | "red.200" | "red.300" | "green.100" | "green.200" | "green.300";

... but as you can see, as either of the list grow, I would have to update the type colorScheme manually. How do I get the type colorShade without having to manually edit colorScheme directly?

CodePudding user response:

You can use a feature called template literal types:

type colorShade = `${color}.${shade}`

Docs: https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

  • Related