Michael
Michael

Reputation: 7113

Puppeteer / Typescript: How can I cast to Element in a eval$ page function?

I try to read the value of an attribute in puppeteer:

const value = attribute && await page.$eval(selector, (node: Element, name: string) => {
    return node.getAttribute(name)
}, attribute.name);

which results in

error TS2339: Property 'getAttribute' does not exist on type 'Element'.

When I cast

node: any

instead of node: Element, it works fine.

The reason for this seems to be that React overloads the type as

interface Element { }

in node_modules/@types/react/gloabal.d.ts

How can I cast to the standard Element?

Upvotes: 2

Views: 2999

Answers (1)

x1n13y84issmd42
x1n13y84issmd42

Reputation: 970

You may be missing the dom lib from your tsconfig.json. Add it as follows:

"lib": [
    "dom",
    "es2018"
],

If adding the lib doesn't help, try declaring the needed method explicitly with declaration merging:

interface Element {
    getAttribute(name: string): string;
}

With that you can extend arbitrary type as you like.

Upvotes: 3

Related Questions