7
votes

I am trying to extend puppeteer's class ElementHandle with one method. I have checked some examples and wrote simple code just like in this answer.

But VSCode shows me an error for the line where I change ElementHandle prototype:

'ElementHandle' only refers to a type, but is being used as a value here.ts(2693)

How can I fix it?

My code:

import { ElementHandle } from 'puppeteer';

declare module 'puppeteer' {
    interface ElementHandle {
        scrollIntoView(): void;
    }
}

ElementHandle.prototype.scrollIntoView = async function (): Promise<void> {
    await this._scrollIntoViewIfNeeded();
}

ElementHandle class: https://github.com/puppeteer/puppeteer/blob/master/src/JSHandle.js

1

1 Answers

1
votes

The error message you are seeing is accurate: in the case of Puppeter, the ElementHandle refers to a type, not to a class / object / value.

In Typescript, types exist only at compile-time. Then, at run-time, they don't exist at all, they are completely removed.

For this reason, the statement:

ElementHandle.prototype.scrollIntoView = async function() { /* */ }

Won't work. Since ElementHandle is a only type, it won't exist on runtime, so you can't send the .prototype message in an attempt to access to it.

An interpretation here would be that ElementHandle is just an abstract representation of some entities handled by puppeteer, not a reference that has entity and/or can be used as a template, like a class.

Therefore, it's just not possible to assign a function (or any value, for that matter) to it "extend" it like you want to do.