Reputation:
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. Why I can't able to use the object property value on 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');
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)`
Upvotes: 0
Views: 41
Reputation: 1155
This is because your style
parameter has a generic object type. You can make it more specific to solve this issue with
style: { [index: string]: string } = {
height: "100px",
width: "100px",
border: "1px solid red",
}
Upvotes: 1