带有重载的函数上的prototype.apply()

时间:2019-01-21 11:29:19

标签: typescript

如果我尝试扩展一个函数而不扩展整个类。 因此,在此NodeJS http module中,我想重新定义response.end函数,执行我的逻辑,并最后调用原始的response.end

问题在于end函数具有3个重载。因此,我不能将其与rest参数“ args”一起应用。我已经尝试了所有可能的参数元组的联合类型,但仍然没有用。

错误提示:

Type '(...args: [any, (string | undefined)?, ((() => void) | undefined)?] |         
    [any, ((() => void) | undefined)?] | [any]) => void' is not assignable to 
    type '{ (cb?: (() => void) | undefined): void; (chunk: any, cb?: (() => 
    void) | undefined): void; (chunk: any, encoding?: string | undefined, cb?: 
    (() => void) | undefined): void; }'.
    Types of parameters 'args' and 'cb' are incompatible.
    Type '[((() => void) | undefined)?]' is not assignable to type '[any, 
    (string | undefined)?, ((() => void) | undefined)?] | [any, ((() => void) | 
    undefined)?] | [any]'.
    Type '[((() => void) | undefined)?]' is not assignable to type '[any]'.
    Property '0' is optional in type '[((() => void) | undefined)?]' but 
    required in type '[any]'.

AND

Argument of type '[any, (string | undefined)?, ((() => void) | undefined)?] 
    | [any, ((() => void) | undefined)?] | [any]' is not assignable to 
    parameter of type '[any, (string | undefined)?, ((() => void) | 
    undefined)?]'.
    Type '[any, ((() => void) | undefined)?]' is not assignable to type '[any, 
    (string | undefined)?, ((() => void) | undefined)?]'.
    Types of property '1' are incompatible.
    Type '(() => void) | undefined' is not assignable to type 'string | 
    undefined'.
    Type '() => void' is not assignable to type 'string'.

我当前的解决方法是使用@ ts-ignore装饰器:

const end = res.end;
res.end = function(...args: any[]): void {
    // .....
    res.end = end;

    // @ts-ignore, apply any[] args as end has several overloads
    res.end.apply(this, args);
    // ......
};

我希望工作的代码是通过将args定义为所有重载参数元组的联合类型:

res.end = function(...args: [any, string?, (() => void)?] | [any, (() => 
                  void)?]): void {
   // my logic ....
   res.end = end;

   res.end.apply(this, args);
   // rest of my logic
 };

0 个答案:

没有答案
相关问题