Understanding Arrow Functions

Overview

Welcome back to the cosmos of learning functions in TypeScript! In this voyage, you will learn how to define functions, handle optional and default parameters in these functions, and utilize arrow functions. These skills will help you craft effective and flexible TypeScript functions.

TypeScript Functions and Parameters

Let's learn more ways of working with functions in TypeScript. Although functions can be declared and used in a way similar to JavaScript, TypeScript offers a few more flexible options when dealing with parameters. Let's start with the basic definition:

function checkBaseID(baseID: number): void {
  // If the ID is invalid, log an error message
  if (baseID <= 0) {
    console.log("Invalid ID!");
  }
}

checkBaseID(-10); // prints "Invalid ID!"

In the above example, baseID is a parameter of the function and has a type number. The function does not return anything; hence, the return type is void.

Optional and Default Parameters within TypeScript Functions

One of TypeScript's additional features includes optional and default parameters. Here, we define a function with an optional parameter and a default parameter:

function shipmentDetails(baseID: number, isInsured?: boolean, insuranceAmount: number = 0): void {
  console.log('Base ID:', baseID);
  console.log('Is Insured:', isInsured ? 'Yes' : 'No');
  if(isInsured) {
    console.log('Insurance Amount:', insuranceAmount);
  }
}

shipmentDetails(101, true, 5000); // Base ID: 101, Is Insured: Yes, Insurance Amount: 5000
shipmentDetails(102); // Base ID: 102, Is Insured: No

In the shipmentDetails function, isInsured is an optional parameter, and insuranceAmount is a default parameter. The optional parameters and those with a default value must always come after the required parameters.

Arrow Functions in TypeScript

Arrow functions in TypeScript introduce a concise syntax for writing functions, focusing on simplifying function expressions. Unlike traditional function expressions, arrow functions capture the context of where they are defined, not where they are called. For now, we will concentrate on their syntax and straightforward use cases.

Let's explore the syntax through examples:

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal