Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3169

Redundancy in writing type for function

One of the simplest type for function in TypeScript looks like:

let myAdd: (x: number, y: number) => number = function (
  x: number,
  y: number
): number {
  return x + y;
};

What is the purpose of redundancy of that? I can not understand it.

Upvotes: 2

Views: 380

Answers (1)

jabuj
jabuj

Reputation: 3649

That's not really the simplest type, I'd even argue that this is a bit overcomplicated. Usually if I create such function, I'll write this:

function myAdd(x: number, y: number) {
  return x + y;
}

Here the return type is inferred. If you specifically want to use Function Expression and not function declaration, it's the same:

const myAdd = function(x: number, y: number) {
  return x + y;
}

Here the return type and myAdd variable types will also be inferred. You almost never need to annotate every single thing. In fact, the only thing I usually have to annotate are function parameters unless I write abstract classes or interfaces where everything must be definitely typed. TypeScript is ridiculously good at type inference, so most of types can be harmlessly omitted.

Upvotes: 2

Related Questions