Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript extending third party class error: ElementHandle only refers to a type, but is being used as a value here

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

like image 332
DJ-Glock Avatar asked Nov 26 '19 09:11

DJ-Glock


1 Answers

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.

like image 59
tmilar Avatar answered Nov 03 '22 12:11

tmilar