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:
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:
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:
