我尝试在类方法上应用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之外,所以我希望在这种情况下也支持它?
答案 0 :(得分:2)
问题是对于具有实现的函数,最后一个签名是实现签名,并且不公开:
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");