下面给出的代码中foo1
和foo2
的类型推断有什么区别:
interface myInterface {
foo1(args: string): void;
foo2: (args: string) => void;
}
两者的类型推断是否不同?还有什么时候使用哪一个?
最佳答案
在界面上,几乎没有区别。您可以根据自己的喜好混合搭配这两种风格:
interface myInterface {
foo1(args: string): void;
foo2: (args: string) => void;
}
class C implements myInterface {
foo1: (args: string) => void = (args) => {
}
foo2(args: string) {
}
}
此外,两者在运行时完全可以互换:
declare const i: myInterface;
const c = new C;
// no errors
c.foo1 = i.foo2;
i.foo1 = c.foo2;
c.foo2 = i.foo1;
i.foo2 = c.foo1;
有一个影响类型推断的差异:--strictFunctionTypes标志不适用于方法,因此在严格模式下,当参数和返回类型不同时,方法和函数属性具有不同的兼容性规则。
另一个区别是您可以将属性声明为只读,以防止分配给它。你不能用一个方法来做到这一点(但你仍然可以用 Readonly<myInterface>
声明另一种类型,它的所有属性和方法都是只读的)。
interface myInterface {
foo1(args: string): void;
readonly foo2: (args: string) => void;
}
i.foo2 = c.foo1; // this is an error now
但是在类中,它们是不同的,可能是因为方法是在运行时在类原型(prototype)对象上定义的,而属性是在为构造函数生成的代码中初始化的,所以不可能用方法覆盖属性:
class C2 extends C {
foo1(args: string) { // error: Class 'C' defines instance member property 'foo1',
// but extended class 'C2' defines it as instance member function.
}
foo2: (args: string) => void = (args) => { // Ok
}
}
关于typescript - 箭头功能与界面内的普通功能之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884489/