简体   繁体   中英

How to fix property does not exist on type 'Element' error in Typescript?

I get an error when I run a build. It says

TS2339: Property 'body' does not exist on type 'Element'.

The code look likes:

const testCode = document.createElementNS('http://example.com/x/x', 'testtestCode');
testCode.body = widgetBody; 

Tried to add 'as Element' or instanceof after the const, but that didn't work. Any suggestions?

After more information in the comments, it's clear that you want to use custom properties on a custom element. You can do it like this:

interface MyCustomElement {
    body: string;
    model: string;
}

const testCode = document.createElementNS('http://example.com/x/x', 'testtestCode')
                 as Element & MyCustomElement;
testCode.body = widgetBody; 

Casting the variable as Element & MyCustomElement will let you access the normal properties of the Element type while also being able to access your custom properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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