how to set multiple CSS style properties in typescript for an element?

前端 未结 4 1671
有刺的猬
有刺的猬 2021-02-12 20:09

Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.

public static setStyleAttribute(ele         


        
4条回答
  •  甜味超标
    2021-02-12 21:04

    Just a little late to the party, but anyway...

    The actual problem is not that style is not defined on Element. The word Element at the beginning of Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration is just the first word in a sentence and therefore uppercased. Means it does not relate in any way to the Element object - which is quite confusing.

    However, the error message means that you are trying to access a property using the subscript operator [] with an incorrectly typed index. In your case your key is of type string but HTMLElement.style is a CSSStyleDeclaration object which has an index signature of [index: number]: string and consequently requires your key to be of type number.

    The index signature comes from the typescript/lib/lib.dom.d.ts declaration file in your TypeScript installation. There you will find CSSStyleDeclaration.

    So what you can do is simply cast to any like so:

    (element.style)[key] = attr[key];
    

    It's not the best solution but it works and is straightforward. It also does not require you to stringify your styles like it would be necessary when you use element.setAttribute.

提交回复
热议问题