在typescript中给定以下Code

const compareFn = {
    numberAsc: function (a: number, b: number) { return a - b },
    numberDesc: function (a: number, b: number) { return b - a },
};

[2, 1, "nope"].sort(compareFn.numberDesc);

typescript - 在单类型参数上接受混合类型的使用-LMLPHP
我的函数numberDesc只接受number类型的属性。但是sort将同时对其应用numberstring。这是错误的,但被typescript接受。
我的猜测是,typescript期望sort()函数是一个comparefn,它接受数字或字符串,但严格来说不是两者都接受。但在我看来,它应该只允许接受数字和字符串的函数。
这是“bug”还是typescript打算这样做?
但最重要的是:我能让它发挥作用吗?给定的数组应该只接受兼容的排序函数。
请注意,它在这里工作正常:
typescript - 在单类型参数上接受混合类型的使用-LMLPHP

最佳答案

这就是你所拥有的:

type Foo = (a:number,b:number)=>number;
type Bar = (a:number|string,b:number|string)=>number|string;

let foo:Foo;
let bar:Bar;
bar = foo; // Why is this valid!

其有效,因为以下内容有效:
let x:number;
let y:number|string;
y = x; // Valid for obvious reasons

在检查函数兼容性时,在两个方向检查参数兼容性。
更多信息请点击:https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Type%20Compatibility.md#comparing-two-functions
这是“bug”还是typescript打算这样做?
打算那样做。
但最重要的是:我能让它发挥作用吗?给定的数组应该只接受兼容的排序函数。
没有,正如解释的那样,类型化中兼容函数的语义允许双方差。

09-30 16:34
查看更多