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