gpt4 book ai didi

typescript - 在单一类型参数上接受混合类型的使用

转载 作者:搜寻专家 更新时间:2023-10-30 21:43:04 25 4
gpt4 key购买 nike

给定以下 Code在 typescript 中:

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);

enter image description here

我的函数 numberDesc 只接受 number 类型的属性。然而,sort 将对它应用 numberstring。这是错误的,但被 TypeScript 接受。

我的猜测是 TypeScript 期望 sort() 函数接受数字或字符串的 compareFn,但严格来说不能同时接受这两者。但是在我看来,它应该只允许接受数字和字符串的函数。

这是一个“错误”还是 TypeScript 打算这样做?
但最重要的是:我能让它发挥作用吗?给定一个数组应该只接受兼容的排序函数。


请注意,它在这里工作正常: enter image description here

最佳答案

这就是你所拥有的:

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

Is this a "Bug" or does TypeScript intend to behave like that?

打算那样做。

But most importantly: can I make it work? Given an array is should only accept compatible sort-functions.

没有。如解释的那样,TypeScript 中兼容函数的语义允许双变。

关于typescript - 在单一类型参数上接受混合类型的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com