Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - Arrow Functions

These are anonymous functions with a simple syntax. They do not use the keyword function. The body of the function is defined and assigned to a variable. Using const is safer than using var or let, because a function expression is always constant value.

const {name} = ({optional parameter: type}, {optional parameter: type}, etc): {return type} => {function body};
const DailyPay = (hourlyRate : number, hours : number, bonus? : number): number => { (hourlyRate * hours) + bonus; };
  • Do not use the function keyword. const is preferred.
  • A regular function cares very much who calls it. The value of the this inside a regular function depends on HOW the function was called - the object that made the call. this can vary.
  • An arrow function does not care who calls it and it's this keyword inside the arrow function depends on WHERE the function was defined (the scope of the defined function).
  • You can omit the curly braces if you can define your return statement (function body) in one line. See example 1
  • If you use curly braces to define your return statement (function body), then you must include a return statement. See example 4.
  • They are not well suited for defining object methods.

For example (arrows), if your arrow function is defined in a class, the this will always be that Class regardless of who calls it. This is a fundamental difference from standard js functions.


// example 1
let squareIt = (x: number) => x * x;

// example 1a
// If you have one and only one parameter AND you don't want use a type-annotation, you can
// skip the parenthesis. I personally prefer them.
let squareIt = x => x * x;

// this is more declarative
let squareIt = (x) => x * x;

// example 2
let addIt = (a: number, b: number) => a + b;

// example 3
let greeting = () => "hello!";

// example 4
// since I have multiple lines of code, I need to use curly-braces.
let scores: number[] = [15,45,55,75,90];
let highScores: number[];
highScores = scores.filter((element) =>
{
    if(element > 70)
    {
        return true;
    }
    return false;
});

Example 1
Example 2
Example 3
Example 4