2

Currently, I am learning TypeScript. I am quite confused about the difference between keyword function and => (fat arrow). Please see the code below:

interface Counter {
    (start: number);
    interval: number;
    reset() : void;
}

let a = <Counter>function(start: number) { };
let b = <Counter>(start: number) => { };

a.reset(); //OK
b.reset(); //error: Property 'reset' does not exist on type <Counter>(start: number) => void

It seems that fat arrow doesn't work the same as keyword function.

Cœur
  • 32,421
  • 21
  • 173
  • 232
user3496167
  • 155
  • 3
  • 10
  • This has nothing to do with TypeScript. It is purely a JS (ES6) issue. The difference is well explained in hundreds of blog posts, documentation pages, and questions right here on SO. –  Dec 13 '16 at 07:31
  • @torazaburo Got it. Thanks a lot. – user3496167 Dec 13 '16 at 07:43

2 Answers2

3

fat arrow functions have a shorter syntax compared to function expressions and lexically bind the this value. Arrow functions are always anonymous and effectively turn function (arguments) { return expression; } into (arguments) => expression. If using an expression after an arrow, the return is implicit, so no return is required.

  • 2
    The term "fat arrow function" is obsolete. The correct term is "arrow function". –  Dec 13 '16 at 07:33
2

It's all about keeping the context/scope in JavaScript. Take a look here: What is this in JavaScript and Typescript.

Dawid Rutkowski
  • 2,486
  • 1
  • 27
  • 31