无法为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
相关产品推荐
相关产品推荐

