首页 > 解决方案 > 在 for 循环中使用对象属性时出错(TypeScript)

问题描述

我有一个简单的函数,在这个函数内部它循环一个对象并尝试使用对象属性值,但它得到一个错误。为什么我不能使用对象属性值style[key]

let createFunction = function (
    elmName: string,
    style: object = {
        height: '100px',
        width: '100px',
        border: '1px solid red'
    }
): void {

    let
        newELM = document.createElement(elmName);

    let customStyle : any = '';

    //set the style to custom style
    for (let key in style ){
        if (style.hasOwnProperty(key)){
            customStyle += key + ':' + style[key] + ';'; //___________ERROR on style[key]
        }
    }

    newELM.setAttribute('style', customStyle);

    if (window){
        document.body.appendChild(newELM);
    }
}

createFunction('div');

错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)`

标签: javascripttypescript

解决方案


这是因为您的style参数具有通用对象类型。您可以更具体地解决此问题

style: { [index: string]: string } = {
    height: "100px",
    width: "100px",
    border: "1px solid red",
}

推荐阅读