简体   繁体   English

在 for 循环中使用 object 属性时出错(TypeScript)

[英]Error on use object property in for loop (TypeScript)

I have a simple function, Inside this function it loops a object and try to use the object property value but it gets an error.我有一个简单的 function,在这个 function 里面,它循环了一个 object 并尝试使用 ZA8CFFDE6331BD4B626ZZ 属性,但它得到了一个错误,但它得到了一个错误。 Why I can't able to use the object property value on style[key]为什么我不能在style[key]上使用 object 属性值

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');

Error:错误:

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)`

This is because your style parameter has a generic object type.这是因为您的style参数具有通用 object 类型。 You can make it more specific to solve this issue with您可以更具体地解决此问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM