【发布时间】:2021-01-19 05:25:23
【问题描述】:
我正在创建一个对象来存储一堆 RGB 颜色,并且允许嵌套。所以在循环对象时,我需要查看哪些键对应于 RGB 值或对象。但是,我尝试过的每个类型保护都不会真正缩小类型范围。
type Color = [number, number, number] | 'transparent'
type ColorGroup = Record<string, Color>
type Colors = Record<string, Color | ColorGroup>
const colors: Colors = {
black: [0, 0, 0],
white: [255, 255, 255],
transparent: 'transparent',
primary: {
'50': [211, 233, 252],
'100': [179, 213, 248],
'200': [127, 185, 251],
'300': [68, 156, 253],
'400': [0, 126, 254],
'500': [13, 100, 226],
'600': [17, 79, 189],
'700': [15, 62, 157],
'800': [10, 46, 122],
'900': [1, 22, 77],
}
}
const isColor = (color: Color | ColorGroup): color is Color => {
return Array.isArray(color) || typeof color === 'string'
}
const usesColor = (color: Color):void => {
// does something with the color
}
for(const color in colors) {
if(isColor(colors[color])) usesColor(colors[color]) // error: type 'Record<string, Color>' is not assignable to type 'Color'
}
有什么想法吗?我只是错过了一些关于类型保护的基本知识吗?
【问题讨论】:
-
类型保护没问题。问题在于检查
colors[color]。如果将当前颜色分配给中间变量并检查该变量,则它可以工作。
标签: typescript typeguards