Search code examples
htmltypescripthtmlelements

No index signature with a parameter of type 'string' was found on type 'HTMLScriptElement'


I have an issue with the type of attributes of HTMLScriptElement.

In the below code, the issue come at line:

script[attribute.name] = attribute.value ? attribute.value : true

with the hint: "TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'HTMLScriptElement'.   No index signature with a parameter of type 'string' was found on type 'HTMLScriptElement'."

const generateFromSource = (codeString: string) => {
    let script = document.createElement('script')
    let template = document.createElement('div')
    template.innerHTML = codeString

    const element = template.getElementsByTagName('script')[0]
    for (let attribute of element.attributes) {
        if (attribute) {
            script[attribute.name] = attribute.value ? attribute.value : true
        }
    }
    document.head.appendChild(script)
}

Please help me with some suggestions. Thank you!


Solution

  • Indexing script local in order to get particular attribute hardly will work in JS: script.getAttribute(attributeName) will. Setting particular script's attribute value might be done this way:

    script.setAttribute(attribute.name, attribute.value);