Difference between named functional syntax in Typescript interface declaration

There seem to be two ways to declare a named function in an interface in Typescript:

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

Two questions:

  • What is the difference between foo and bar functions?
  • Why is there only readonly modifier for the panel?

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"

It seems to me that both ways of declaring are equivalent, except that the second way can be done read-only.

I also found this older answer saying that they are equivalent, with the exception of the possibility of overload.

+4
source share
1 answer

Both of them are valid and generate the same Javascript code:

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

:

  • foo bar?

(), . typescript bar fpo .

  1. readonly?

readonly

+2

Source: https://habr.com/ru/post/1677066/


All Articles