Home > Blockchain >  String Literal Types union with string type
String Literal Types union with string type

Time:06-21

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?

CodePudding user response:

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.

  • Related