我想知道在Typescript中方法头部的 => 和 : 有什么区别?谢谢
methodA: (
fieldA: string,
) => interfaceA;
methodA(
fieldA: string
): interfaceA;
我想知道在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
中的methodA
const期望一个string
参数,而TS不会抱怨,而根据Bivariant
接口,它也可能是一个number
。反过来,函数foo
允许您使用number
调用arg.methodA
。
现在,请尝试使用箭头函数重新编写Bivariance
接口:
interface Bivariant {
methodA:(fieldA: string | number) => void;
}
你会收到一个错误。
除此之外,请检查: