【问题标题】:Puppeteer / Typescript: How can I cast to Element in a eval$ page function?Puppeteer / Typescript:如何在 eval$ 页面函数中转换为 Element?
【发布时间】:2020-04-02 21:46:06
【问题描述】:

我尝试读取 puppeteer 中某个属性的值:

const value = attribute && await page.$eval(selector, (node: Element, name: string) => {
    return node.getAttribute(name)
}, attribute.name);

导致

错误 TS2339:“元素”类型上不存在属性“getAttribute”。

当我施放时

节点:任意

代替节点:元素,它工作正常。

这样做的原因似乎是 React 将类型重载为

界面元素{ }

在 node_modules/@types/react/gloabal.d.ts 中

如何转换为标准元素?

【问题讨论】:

标签: typescript element puppeteer getattribute


【解决方案1】:

您可能缺少tsconfig.json 中的dom 库。添加如下:

"lib": [
    "dom",
    "es2018"
],

如果添加 lib 没有帮助,请尝试使用 declaration merging 显式声明所需的方法:

interface Element {
    getAttribute(name: string): string;
}

你可以随意扩展任意类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多