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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM