typescript - 箭头功能与界面内的普通功能之间的区别

标签 typescript

下面给出的代码中foo1foo2的类型推断有什么区别:

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/

相关文章:

javascript - 如何在文件来自 JSON 的 Angular 中编辑和更新数组项

angular - 完成for循环后如何完成订阅者?

javascript - Nest.js - 根据 header 值跳过中间件

Angular2 和 ReactiveX 的分页思路

node.js - tsc 生成的 .d.ts 文件给出错误 "Cannot find namespace ' Jimp'"

javascript - 如何使用 angular cli 默认试运行

reactjs - 在 react typescript 中指定文件上传事件的类型

javascript - Firebase 存储连接到 Angular 应用

Angular:扩展服务和传递参数

css - Angular Material design 复选框黑色前景色(符号颜色)