1

I have a lot of (tailwind) color strings, which I would like to restrict my type system to. For demo purposes I just display 3*3 here:

text-red-500    text-red-700    text-red-900
text-amber-500  text-amber-700  text-amber-900
text-yellow-500 text-yellow-700 text-yellow-900

I would like to do something like:

type Color = "red" | "amber" | "yellow"
type Tint = "500" | "700" | "900"
type TailwindColor = "text-" + Color + "-" + Tint

Is there a way for me to do this in Typescript?

1 Answer 1

3

You can use template string types:

type Color = "red" | "amber" | "yellow"
type Tint = "500" | "700" | "900"
type TailwindColor = `text-${Color}-${Tint}`

Playground Link

You should take care though such combinatorial unions will tend to slow down the compiler if they get to large, and there are limits to the maximum size of a union that TypeScript will allow (not sure what it is, but there is a hard limit, ex)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.