想知道 => 和 : 在 Typescript 的方法头中有什么区别?谢谢
methodA: (
fieldA: string,
) => interfaceA;
methodA(
fieldA: string
): interfaceA;
最佳答案
区别很大。方法是双变的。这意味着使用它们是不安全的。考虑这个例子
interface Bivariant {
methodA(fieldA: string | number): void;
}
const bivariant: Bivariant = {
methodA(fieldA: string) { // string is assignable to `fieldA` argument, not safe because it might be a number
fieldA.includes('a')
}
}
const foo = (arg: Bivariant) => {
arg.methodA(42) // ok
}
foo(bivariant) // runtime error, no TS error
请运行这段代码。您将遇到运行时错误,因为 bivariant
const 中的 methodA
需要一个 string
参数,而 TS 不会提示,而根据 Bivariant
接口(interface)它也可能是一个数字
。反过来,函数 foo
允许您使用 number
调用 arg.methodA
。
现在,尝试用箭头函数重写Bivariance
接口(interface):
interface Bivariant {
methodA:(fieldA: string | number) => void;
}
你会得到一个错误。
除此之外,检查:
- this article
斯蒂芬博耶
, - this video Titian-Cernicova-Dragomir 的谈话和
- 我的question我在这里列出了所有关于 *-variance 的链接,因为这个主题非常有趣。
- here你可以在我的文章中找到一些 TS 突变的例子
关于typescript - => 和 : in Typescript 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73508157/