0

I want to use the intellisense of typescript on some predefined colors in my component's prop. But user can also pass any hex color into that prop too.

type PREDEFINED_COLORS = 'success' | 'error' | 'info'; type Props = { color: PREDEFINED_COLORS | string; } 

I know PREDEFINED_COLORS is also a string but i believe there should be some workarounds to achieve the benefits of intellisense.

Do you have any suggestions?

3
  • you could prefix abritrary hex strings with # -> color: PREDEFINED_COLORS | '#${string}' Commented Jun 21, 2022 at 9:15
  • Type '"testColor"' is not assignable to type 'COLOR_MAP_TYPES | "#${string}" | undefined' Commented Jun 21, 2022 at 9:33
  • If you are interested in validating HEX strings, you can check my article. Also, it is possible only with extra function Commented Jun 21, 2022 at 10:14

1 Answer 1

1

Your safest bet would be to use a templated string type. Something like this:

type PREDEFINED_COLORS = 'success' | 'error' | 'info'; type Props = { color: PREDEFINED_COLORS | `#${string}`; } 

You may try to narrow the type even more, creating a hexDigit and then building the entire type from there. Something like this:

type hexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' type hexColor = `#${hexDigit}${hexDigit}${hexDigit}${hexDigit}${hexDigit}${hexDigit}` 

The problem with this is that TS will generate the entire crossproduct of the hexDigit type and that will end up being a huge type. More exactly it will have 2^32 items which is way above the 100k limit they have. You can more about this here.

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

2 Comments

I'm getting that error when trying with PREDEFINED_COLORS | #${string}; Type '"ffffff"' is not assignable to type 'PREDEFINED_COLORS | #${string} | undefined'.ts(2322)
That's because there's and added # at the start of the string, this means that "ffffff" is not valid, but "#ffffff" is

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.