Reputation: 36069
I'm getting an error TS2339: Property 'on' does not exist on type 'ClientRequest'.
while I'm defining an extension method:
export {};
import {ClientRequest} from 'https';
declare module 'https' {
class ClientRequest {
loadData<T>(): Promise<T>;
}
}
// // eslint-disable-next-line no-extend-native
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;
};
Upvotes: 0
Views: 56
Reputation: 36069
I was importing from the wrong module https
instead of http
, but TypeScript compiler didn't flag it as an error for some reason.
Working code:
export {};
import {ClientRequest} from 'http';
// eslint-disable-next-line max-len
// Check how to import this module, so the extension property is accessible: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#augmenting-globalmodule-scope-from-modules:~:text=%22./observable%22%3B-,import%20%22./map%22%3B,-let%20o%3A
declare module 'http' {
export interface ClientRequest {
plan: string;
data<T>(): Promise<T>;
}
}
// // eslint-disable-next-line no-extend-native
ClientRequest.prototype.data = async function <T>() {
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;
};
Upvotes: 0