typescript - 函数属性与方法

标签 typescript

定义接口(interface)方法之间有什么实际区别:

interface Foo {
    bar(): void;
}

并定义一个函数类型的属性:

interface Foo {
    bar: () => void;
}

?

最佳答案

还有一个区别,readonly 修饰符不能应用于方法。因此,无法阻止以下分配:

interface Foo {
    bar(): void;
}

declare var x: Foo;
x.bar = function () { };

如果 bar 被定义为属性,则可以对其应用 readonly 修饰符:

interface Foo {
    readonly bar: () => void;
}

防止重新分配。

( Playground )

关于typescript - 函数属性与方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156315/

相关文章:

reactjs - typescript :找不到模块 'react'

visual-studio - TypeScript build设置 "Compile on Save"在 VS 2015 中不起作用,.js 文件仅在构建期间生成

node.js - NestJS 基于接口(interface)注入(inject)自定义 TypeOrm 存储库

javascript - 来自组件的 Angular 2 getBoundingClientRect

angular - 引用错误: describe is not defined Karma jasmine angular2

unit-testing - Angular 2 单元测试 : Cannot find name 'describe'

typescript - typescript 中的抽象函数返回类型

typescript - 使用 webpack 从 html 文件加载挖空模板

typescript - Threejs 几何和 TypeScript

typescript - 使用 SolidJS 中的 fetch API 渲染远程数据