Hnry Cn
Hnry Cn

Reputation: 39

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?

Upvotes: 0

Views: 1995

Answers (1)

Micha Schwab
Micha Schwab

Reputation: 798

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.

Upvotes: 1

Related Questions