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

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

我正在尝试扩展 puppeteer's class ElementHandle with one method. I have checked some examples and wrote simple code just like in

但是 VSCode 显示我更改 ElementHandle 原型的行的错误:

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

我该如何解决?

我的代码:

import { ElementHandle } from 'puppeteer';

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

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

元素句柄class: https://github.com/puppeteer/puppeteer/blob/master/src/JSHandle.js

您看到的错误消息是准确的:在 Puppeter 的情况下,ElementHandle 指的是 type,而不是 class /对象/值。

在 Typescript 中,类型仅在编译时存在。然后,在 运行 时间,它们根本不存在,它们被完全删除。

为此,声明:

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

行不通。由于 ElementHandle 是唯一的 类型 ,它不会在 运行 时间存在,因此您无法发送 .prototype 消息来尝试访问它.

这里的解释是 ElementHandle 只是 puppeteer 处理的某些实体的抽象 表示 ,而不是具有实体 and/or 的引用用作模板,如 class.

因此,不可能向它分配一个函数(或任何值,就此而言)并像您想要的那样“扩展”它。