简体   繁体   English

字符串文字类型与字符串类型的联合

[英]String Literal Types union with string type

I want to use the intellisense of typescript on some predefined colors in my component's prop.我想在我的组件道具中的一些预定义颜色上使用 typescript 的智能感知。 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.我知道PREDEFINED_COLORS也是一个字符串,但我相信应该有一些解决方法来实现智能感知的好处。

Do you have any suggestions?你有什么建议吗?

Your safest bet would be to use a templated string type .您最安全的选择是使用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.您可以尝试进一步缩小类型,创建一个 hexDigit,然后从那里构建整个类型。 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.这样做的问题是 TS 将生成hexDigit类型的整个叉积,最终将成为一个巨大的类型。 More exactly it will have 2^32 items which is way above the 100k limit they have.更确切地说,它将有 2^32 个项目,远远高于他们拥有的 100k 限制。 You can more about this here .你可以在这里了解更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM