TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'

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];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章