首页 > 解决方案 > 用 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

标签: node.jstypescriptexpress

解决方案


问题

您的初始签名未通过编译器检查,因为继承endServerResponse自的函数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;
    }
  }
};

推荐阅读