【问题标题】:Difference between named function syntax in Typescript interface declarationTypescript接口声明中命名函数语法的区别
【发布时间】:2017-10-12 15:42:54
【问题描述】:

似乎有两种方法可以在 Typescript 的接口中声明命名函数:

export interface Zoo {
  foo(): string
  readonly bar: () => string,
}

两个问题:

  1. foo 和 bar 函数有什么区别?
  2. 为什么只有 bar 可以有 readonly 修饰符?

更新:

这是一个更长的例子:

export interface Zoo {
  foo(): string
  readonly bar: () => string,
}

export const x: Zoo = {
  foo: () => "a",
  bar: () => "a",
};

x.foo = () => "b"; // No error
x.bar = () => "b"; // Error: Cannot assign to "bar"

在我看来,两种声明方式都是等价的,只是第二种方式可以设为只读。

我还发现 this 较早的答案说它们是等效的,除了可能超载。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    它们都是有效的,并且生成相同的 Javascript 代码:

    exports.x = {
        foo: function () { return "a"; },
        bar: function () { return "a"; }
    };
    

    但您确实可以将 readonly 修饰符仅分配给属性。

    而且旧答案仍然有效,第一个可用于重载,第二个否:

    a.ts(2,5): error TS2300: Duplicate identifier 'myFunction'.
    a.ts(3,5): error TS2300: Duplicate identifier 'myFunction'.
    a.ts(3,5): error TS2403: Subsequent variable declarations must have the same type.  Variable 'myFunction' must be of type '(s: string) => void', but here has type '(s: number) => void'.
    

    总结一下:

    1. foo 和 bar 函数有什么区别?

    代码被(反)编译后,没有。之前,typescript 使用 bar 作为属性,fpo 作为函数。

    1. 为什么只有 bar 可以有 readonly 修饰符?

    因为函数不能有只读修饰符

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 2012-12-30
      • 2017-01-26
      • 2016-12-05
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多