我需要使用下一个签名覆盖方法res.end:
res.end = (data: any, encoding: string)
但是TS返回下一个错误:
Type '(data: any, encoding: string) => void' is not assignable to type '{
(cb?: (() => void) | undefined): void;
(chunk: any, cb?: (() => void) | undefined): void;
(chunk: any, encoding: string, cb?: (() => void) | undefined): void;
}'.ts(2322)
我曾尝试传递空的回调,但并没有帮助:
res.end = (data: any, encoding: string, callback: `() =>void`): void
答案 0 :(得分:2)
将您的函数类型设置为any
,这意味着它可以转换(或分配)为任何类型。
尝试一下
res.end = ((data: any, encoding: string): void => { }) as any;
更新
您可以创建扩展express.Response
的类型,它覆盖end
方法(NodeJS.WritableStream
的方法)。
import { Request, Response, Handler } from 'express';
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
interface MyResponse extends Omit<Response, "end"> {
end: (data: any, encoding: string) => void;
}
const handler: Handler = (req: Request, res: MyResponse) => {
res.end = (data: any, encoding: string) => {
}
};
答案 1 :(得分:2)
您的初始签名未通过编译器检查,因为end
函数具有此重载:
end(cb?: () => void): void;
end(chunk: any, cb?: () => void): void;
end(chunk: any, encoding: string, cb?: () => void): void;
编译器警告您,在运行时,您需要检查正在使用哪些重载。
这里是安全类型的签名。它会检查三个参数中的哪一个是回调,然后采取相应的措施。
import { Response } from 'express';
const handler = (req: Request, res: Response) => {
res.end = (arg1: Function | any, arg2?: Function | string, arg3?: Function) => {
if (typeof arg1 === 'function') {
// end(cb?: () => void): void;
}
if (typeof arg2 === 'function') {
// end(chunk: any, cb?: () => void): void;
}
if (typeof arg3 === 'function') {
// end(chunk: any, encoding: string, cb?: () => void): void;
}
}
};