Reference: TypeScript Arrow Function

TypeScript offers arrow functions, a feature defined in the ES2015 JavaScript language specification, that provides concise syntax for defining anonymous functions.

Rules

  • An arrow function starts with the function parameter list.
    • If there is 0, 2 or more parameters, then the parenthesis () are required.
    • If there is one parameter then the parenthesis is optional.
  • An "arrow" is used to separate the parameter list and the body of the function. The "arrow" is an equal symbol and a greater than symbol. =>
  • If the function body contains 2 or more lines, then the curly braces {} are required. If the body contains one line then the curly braces are optional.
  • "this" is captured at the time of declaration instead of at the time of execution.

Syntax

(param1, param2,...paramN) => {
  line of code 1;
  line of code 2;
  ... line of code N;
}

Examples

Using the arrow function with the Array.forEach function.

let list: Array<number> = [1, 2, 3, 4, 5];
list.forEach((item, index, array) => console.log(item));

Using the arrow function with the jQuery.getJSON function.

$.getJSON(url, (json: any) => console.log(json));
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License