简体   繁体   English

Typescript接口声明中命名函数语法的区别

[英]Difference between named function syntax in Typescript interface declaration

It seems there are two ways to declare a named function in an interface in Typescript: 似乎有两种方法可以在Typescript中的接口中声明一个命名函数:

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

Two questions: 两个问题:

  1. What is the difference between the foo and the bar functions? foo和bar函数有什么区别?
  2. Why can only bar have the readonly modifier? 为什么只有bar才能有readonly修饰符?

UPDATE: 更新:

Here is a longer example: 这是一个较长的例子:

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"

To me it seems that both ways of declaring are equivalent except for that the second way can be made readonly. 对我而言,似乎两种声明方式都是等效的,除非第二种方式可以只读。

I also found this older answer saying they are equivalent except for the possibility to overload. 我还发现这个较老的答案说它们是相同的,除了可能超载。

Both of them are valid and generate the same Javascript code: 它们都有效并生成相同的Javascript代码:

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

But indeed you can assign the readonly modifier only to the property. 但实际上,您只能将readonly修饰符分配给属性。

And the old answer is still valid, the first one can be use for overloaded, the second one no: 旧的答案仍然有效,第一个可以用于重载,第二个没有:

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'.

To summarize: 总结一下:

  1. What is the difference between the foo and the bar functions? foo和bar函数有什么区别?

After the code has been (trans)compiled, none. 代码完成(反式)编译后,没有。 Before, typescript uses bar as a property, and fpo as a function. 之前, fpo使用bar作为属性,使用fpo作为函数。

  1. Why can only bar have the readonly modifier? 为什么只有bar才能有readonly修饰符?

Because function cannot have readonly modifier 因为函数不能有readonly修饰符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM