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

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

Problem Description:

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 – 1

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);
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject