【问题标题】:typescript overload considers only one of the overloaded signatures打字稿重载只考虑重载签名之一
【发布时间】:2018-02-20 18:50:46
【问题描述】:

我正在尝试将 typescript 的方法重载应用于类方法,用于过滤器类方法。

class Vector<T> {
    static of<T>(vals: T[]): Vector<T> {
        return undefined;
    }
    // filter<U extends T>(fn:(x:T)=>x is U): Vector<U>;
    filter(fn:(x:T)=>boolean): this {
        return undefined;
    }
}

const v1 = Vector.of([1,2,3]).filter(x=>x>1);

这工作正常,直到注释行被取消注释。

取消注释该行时,我们收到错误:

ttt.ts(12,38): error TS2345: Argument of type '(x: number) => boolean' is not assignable to parameter of type '(x: number) => x is number'.
  Signature '(x: number): boolean' must be a type predicate.

因此,typescript (2.7.2) 似乎忽略了重载,只选择了 filter 的类型定义之一,我不明白。这种具有重载filter 的模式是相对已知的,而used by typescript's own es5.d.ts,此外还重载is also supported for classes,所以我希望在这种情况下也能支持它?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题在于,对于有实现的函数,最后一个签名是实现签名,不公开:

    class Vector<T> {
        static of<T>(vals: T[]): Vector<T> {
            return undefined;
        }
        filter<U extends T>(fn:(x:T)=>x is U): Vector<U>;
        filter(fn:(x:T)=>boolean): this 
        // Private signature 
        filter(fn:(x:T)=>boolean): this {
            return undefined;
        }
    }
    const v1 = Vector.of([1,2,3]).filter(x=>x>1);
    const v2 = Vector.of([1,2,3, ""]).filter((x) : x is string =>typeof x === "string");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多