首页 > 解决方案 > 打字稿扩展第三方类错误:ElementHandle 仅引用类型,但在此处用作值

问题描述

我正在尝试用一种方法扩展puppeteer的类 ElementHandle 。我已经检查了一些示例并编写了简单的代码,就像在这个答案中一样。

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

'ElementHandle' 仅指一种类型,但在此处用作值。ts(2693)

我该如何解决?

我的代码:

import { ElementHandle } from 'puppeteer';

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

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

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

标签: typescriptinterfaceextension-methodspuppeteer

解决方案


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

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

为此,声明:

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

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

这里的解释是,这ElementHandle只是 puppeteer 处理的某些实体的抽象表示,而不是具有实体和/或可以用作模板的引用,如类。

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


推荐阅读