ts使用枚舉類型引用報錯
解決方案一:在對象接口中使用 keyof typeof 枚舉變量
enum color {
b = 'black',
w = 'white',
g = 'green'
}
interface Style{
bg:keyof typeof color,
[key:string]:string
}
const style:Style = {
bg:'w',
fontSize:'12px'
};
const background = color[style.bg];
解決方案二:使用斷言
enum color {
b = 'black',
w = 'white',
g = 'green'
}
let style= {
bg:'w'
};
const background = color[style.bg as keyof typeof color];