node.js - 用 TypeScript 覆盖 res.end
问题描述
我需要用下一个签名覆盖方法 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
解决方案
问题
您的初始签名未通过编译器检查,因为继承end
ServerResponse
自的函数stream.Writable
具有以下重载:
end(cb?: () => void): void;
end(chunk: any, cb?: () => void): void;
end(chunk: any, encoding: string, cb?: () => void): void;
由于该end
函数具有该重载,因此编译器会警告您,在运行时,您需要检查哪些重载正在使用中。
解决方案
这是一个类型安全的签名。它检查三个参数中的哪一个是回调,然后采取相应的行动。
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;
}
}
};
推荐阅读
- css - 悬停在表格行上时突出显示图像
- python - 在这个方法中如何传递参数?
- list - 如何将数据列表保存到flutter dart中的变量
- c# - 如何在带有ms access数据库的ac#windows窗体中添加条件语句?
- javascript - 修改用 Array.fill() 填充的矩阵的值会修改整列
- java - 使用在 Spring Security 5.2.x 的 spring 服务器之外获得的令牌解析 @RegisteredOAuth2AuthorizedClient
- c - 我的 C 表达式必须具有结构或联合类型
- regex - 使用正则表达式提取匹配模式
- php - Laravel 7.3 路由显示空白页没有错误
- c - 分配给非左值 'uxCurrentEventBits' event_groups.c 时出错