You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript可选参数赋值报错:Puppeteer与Lighthouse类型不兼容

Puppeteer Page类型无法赋值给Lighthouse参数的TS2345错误解决

问题原因

你遇到的是跨模块类型不兼容问题:

  • Lighthouse内部依赖puppeteer-core包的Page类型
  • 你代码里导入的puppeteer包自带了一套独立的Page类
  • 这两个Page类API完全一致,但属于不同模块,且类内部包含私有字段#private,TypeScript会判定它们为不同类型,因此无法直接赋值。

解决方案

方案1:改用puppeteer-core(推荐)

puppeteer本质是puppeteer-core加上浏览器二进制文件,直接使用puppeteer-core可让类型完全对齐:

import lighthouse from "lighthouse";
import puppeteer from "puppeteer-core";
import { executablePath } from "puppeteer";

const browser = await puppeteer.launch({
  executablePath: executablePath(), // 指定浏览器可执行文件路径
});
const page = await browser.newPage();
const result = await lighthouse("https://example.com", undefined, undefined, page);

方案2:类型断言强制兼容(临时方案)

如果不想更换依赖包,可用类型断言绕过TypeScript的类型检查:

import lighthouse from "lighthouse";
import puppeteer from "puppeteer";
import type { Page as CorePage } from "puppeteer-core/lib/types";

const browser = await puppeteer.launch();
const page = await browser.newPage();
const result = await lighthouse("https://example.com", undefined, undefined, page as unknown as CorePage);

⚠️ 注意:此方法仅绕过类型检查,若后续版本出现API差异,可能引发运行时错误。

方案3:确保依赖版本完全一致

检查package.json,确保puppeteer和puppeteer-core的版本完全相同(比如你当前的19.7.5),避免因版本差异导致类型不匹配。


内容的提问来源于stack exchange,提问作者allanberry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:45:20