Scruffy
Scruffy

Reputation: 616

Property 'innerText' does not exist on type 'Element'

I'm using Typescript for Puppeteer. I'm trying to get innerText from an element.

const data = await page.$eval(selector, node => node.innerText);

I'm getting the error:

Property 'innerText' does not exist on type 'Element'

I tried casting to HTMLElement like described in this question: error " Property 'innerText' does not exist on type 'EventTarget' "?

const data = await page.$eval(selector, <HTMLElement>(node: HTMLElement) => node.innerText);

As well as creating my own Interface like this:

interface TextElement extends Element {
    innerText: string;
}

But in each case I'm getting the error that innerText does not exist on this particular type.

Property 'innerText' does not exist on type 'HTMLElement'

Why is this happening and how to deal with this?

Upvotes: 33

Views: 33287

Answers (4)

Emmanuel David
Emmanuel David

Reputation: 411

You can declare a alter the global interface and add innerText to the Element interface

declare global {
  interface Element {
    innerText: string
  }
}

Upvotes: 0

a0m0rajab
a0m0rajab

Reputation: 475

I solved this by using the next syntax:

const title = (document.querySelector(".someselector") as HTMLHeadingElement)?.innerText;

I had to specify the element of the issue. For the question it might be better to use something different than HTMLElement

Upvotes: 0

snnsnn
snnsnn

Reputation: 13698

For those who needs to fix this error for any element returned from querySelector:

const el = document.querySelector<HTMLElement>('#app');

if (el) {
  el.innerText = content;
}

Upvotes: 10

Nenad
Nenad

Reputation: 26717

You can fix it like this:

const data = await page.$eval(selector, node => (node as HTMLElement).innerText);

or:

const data = await page.$eval(selector, node => (<HTMLElement>node).innerText);

UPDATE:

So, after some exchange on Github, it's clear why the syntax from this question does not work. It actually defines anonymous generic function.

<HTMLElement>(node: HTMLElement) => node.innerText

Clearer example would be following:

function myFunction<T>(node: T) {
    node.innerText; // Property 'innerText' does not exist on 'T'
}

const data = await page.$eval(selector, myFunction);

Unfortunate naming of T as HTMLElement creates confusion.

Upvotes: 40

Related Questions