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

无法为Node.js的https.ClientRequest定义扩展方法,报TS2339错误

解决TS2339: Property 'on' does not exist on type 'ClientRequest' 错误

在扩展Node.js的https.ClientRequest添加loadData方法时,遇到TypeScript错误:TS2339: Property 'on' does not exist on type 'ClientRequest'。

原错误代码

export {};

import {ClientRequest} from 'https';

declare module 'https' {
    class ClientRequest {
        loadData<T>(): Promise<T>;
    }
}

ClientRequest.prototype.loadData = async function <T>(this: ClientRequest) {
    const result = new Promise<string>((resolve) => {
        let data = '';
        this.on('response', (res) => {
            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                resolve(data);
            });
        });
    });
    return JSON.parse(await result) as T;
};

错误原因

你在declare module 'https'中重新声明了ClientRequest类,这会覆盖@types/node包中原本的ClientRequest类型定义,导致原有继承自EventEmitter的方法(比如on)被覆盖丢失,因此TypeScript无法识别on属性。

解决方案

Node.js的类型定义里,ClientRequest是用interface而非class声明的,扩展内置类型时必须使用interface来追加方法,这样不会覆盖原有类型的属性和方法:

修改后的正确代码

export {};

import { ClientRequest } from 'https';

declare module 'https' {
    interface ClientRequest {
        loadData<T>(): Promise<T>;
    }
}

ClientRequest.prototype.loadData = async function <T>(this: ClientRequest) {
    const result = new Promise<string>((resolve) => {
        let data = '';
        this.on('response', (res) => {
            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                resolve(data);
            });
        });
    });
    return JSON.parse(await result) as T;
};

额外说明

  • 保留文件顶部的export {},确保文件被TypeScript识别为模块,避免全局作用域冲突。
  • 如果你的ESLint规则禁止扩展原生对象,可以取消注释// eslint-disable-next-line no-extend-native来忽略对应警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:05:16