首页 > 技术文章 > TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'

honkerzh 2020-11-03 11:03 原文

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];

推荐阅读