typescript - 打字稿扩展第三方类错误: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
解决方案
您看到的错误消息是准确的:在 Puppeter 的情况下,ElementHandle
指的是类型,而不是类/对象/值。
在 Typescript 中,类型仅在编译时存在。然后,在运行时,它们根本不存在,它们被完全删除。
为此,声明:
ElementHandle.prototype.scrollIntoView = async function() { /* */ }
不会工作。由于 ElementHandle 是唯一类型,它不会在运行时存在,因此您无法发送.prototype
消息以尝试访问它。
这里的解释是,这ElementHandle
只是 puppeteer 处理的某些实体的抽象表示,而不是具有实体和/或可以用作模板的引用,如类。
因此,不可能像您想要的那样为其“扩展”它分配一个函数(或任何值)。
推荐阅读
- ajax - 检查禁用复选框
- c++ - 将非模板基向下转换为非类型模板子类
- python - Python文件传输(tcp套接字),网络慢的问题
- python - 使用 pandas 解析和编辑 csv
- ios - 有人知道 B2B 应用程序分发在 Apple 中的实际运作方式吗?
- docker - Docker:非法访问:此 Web 应用程序实例已停止
- asp.net - HttpPostedFile 和 SaveAs 不保存路径的一部分
- angular - Angular - 调用 API 重定向到另一个模块
- angular - 使用 Karma 进行角度测试
- android - 根据 if 语句更改视图的背景颜色