我想在组件的道具中的某些预定义的颜色上使用类型记录的intellisense。但是用户也可以将任何十六进制颜色传递到该道具中。
type PREDEFINED_COLORS = 'success' | 'error' | 'info';
type Props = {
color: PREDEFINED_COLORS | string;
}我知道PREDEFINED_COLORS也是一个字符串,但我认为应该有一些解决办法来实现intellisense的好处。
你有什么意见建议?
发布于 2022-06-21 09:33:05
您最安全的选择是使用templated string type。就像这样:
type PREDEFINED_COLORS = 'success' | 'error' | 'info';
type Props = {
color: PREDEFINED_COLORS | `#${string}`;
}您可以尝试进一步缩小类型,创建一个hexDigit,然后从那里构建整个类型。就像这样:
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}`这方面的问题是TS将生成整个hexDigit类型的交叉产品,并最终成为一个巨大的类型。更确切地说,它将有2^32项,这是远远超过100 K的限制,他们有。您可以更多地了解这个这里。
https://stackoverflow.com/questions/72698002
复制相似问题