Function in TypeScript

Function in TypeScript

22 Dec 2023
Intermediate
5.67K Views
8 min read
Learn via Video Course & by Doing Hands-on Labs

TypeScript Programming Course

Functions

The function in TypeScript is fundamental when it comes to other programming languages and TypeScript is no different. functions in TypeScript are pretty similar to JavaScript as it extends them ultimately along with all the required type information and function overloading concepts. The primary advantage is using the typed language is that the developed piece of code will be bug-free as all the values are being scanned against the strict type checking.

TypeScript extends JavaScript functions with typed parameters, return type annotations, overloads, default parameter values, and rest parameters. Like JavaScript, TypeScript functions can be created both as a named function or as an anonymous function.

function.ts

//named function with number as parameters type and return type
function add(x: number, y: number): number {
 return x + y;
}
//anonymous function with number as parameters type and return type
let sum = function (x: number, y: number): number {
 return x + y;
};

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

function.js

function add(x, y) {
 return x + y;
}
var sum = function (x, y) {
 return x + y;
};

Optional Parameters

In JavaScript, you can call a function without passing any arguments, even the function specifies parameters. Hence every parameter in the JavaScript function is optional and when you do this, each parameter value is undefined.

In TypeScript, functions parameters are not optional. The compiler checks each call and warns you if you are not passing the values as per the function receiving parameters type.

TypeScript supports optional parameters by suffixing the question mark '? ' to the parameter. Also, the optional parameters you can add after any required parameters in the parameter list.

optionalparameter.ts

//here, z is optional parameter added after required parameters x and y
function add(x: number, y: number, z?: number): number {
 if (z !== undefined)
 return x + y + z;
 else
 return x + y;
}

let resul1 = add(2, 3); //5
let resul2 = add(2, 3, 5); //10

The compiled JavaScript (ES5) code for the optionalparameter.ts TypeScript code is given below:

optionalparameter.js

function add(x, y, z) {
 if (z !== undefined)
 return x + y + z;
 else
 return x + y;
}
var resul1 = add(2, 3); //5
var resul2 = add(2, 3, 5); //10

Apart from using the optional parameter using? symbol, we can also use the operator called bullish coalescing operator (??) in which we can specify the default parameter value if the value is not being provided with the function parameter is given below.

function add(x: number, y?: number): number { 
 return (x + (y ?? 0)); 
}

Default Parameters

In TypeScript, you can set a default value to a function parameter and when a user does not pass the value for that parameter, the default value will be used for that parameter. Also, default parameter you can add after any required parameters in the parameter list.

defaultparameter.ts

//here, z is default parameter added after required parameters x and y
function add(x: number, y: number, z: number = 0): number {
 return x + y + z;
}

let resul1 = add(2, 3); //5
let resul2 = add(2, 3, 5); //10

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

defaultparameter.js

function add(x, y, z) {
 if (z === void 0) { z = 0; }
 return x + y + z;
}
var resul1 = add(2, 3); //5
var resul2 = add(2, 3, 5); //10

Rest Parameters

The Rest parameters allow you to pass zero or more values to a function. A Rest parameter is prefixed by three consecutive dot characters '…' and allows the functions to have a variable number of arguments without using the arguments object. The rest parameter is an instance of Array, so all array methods work.

A rest parameter must follow the following three rules:

  1. Only one rest parameter is allowed.

  2. The rest parameter type must be an array type.

  3. The rest parameter must be the last parameter in the parameter list.

restparameter.ts

function add(x: number, ...y: number[]): number {
 let result = x;
 for (var i = 0; i < y.length; i++) {
 result += y[i]; 
 }
 return result;
}

let result1 = add(2, 5); //7
let result2 = add(2, 5, 7, 2); //16

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

restparameter.js

function add(x) {
 var y = [];
 for (var _i = 1; _i < arguments.length; _i++) {
 y[_i - 1] = arguments[_i];
 }
 var result = x;
 for (var i = 0; i < y.length; i++) {
 result += y[i];
 }
 return result;
}
var result1 = add(2, 5); //7
var result2 = add(2, 5, 7, 2); //16

Apart from the above example, the rest parameter can be an argument as well, where we can provide the N number of arguments of the array to the variables as given below.

const list_items_1 = []; 
const list_items_2 = [25, 35, 855, 2.96, 77];
list_items_1.push(...list_items_2);

Spread Operator

The spread operator is introduced with ES6. It allows you to expand an array into multiple formal parameters. In ES6, the spread operator example is given below:

spreadoperator_es6.js

function add(x, y, z) {
 return x + y + z;
}

let nums = [2, 5, 5];
let result = add(...nums); //12

In TypeScript, the spread operator acts as a reverse of the rest parameter. The spread operator in TypeScript you can use with rest parameter as given below:

spreadoperator.ts

function add(...x: number[]): number {
 let result = 0;
 for (var i = 0; i < x.length; i++) {
 result += x[i];
 }
 return result;
}

let nums: number[] = [2, 5, 5];
let result = add(...nums); //12

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

spreadoperator.js

function add() {
 var x = [];
 for (var _i = 0; _i < arguments.length; _i++) {
 x[_i - 0] = arguments[_i];
 }
 var result = 0;
 for (var i = 0; i < x.length; i++) {
 result += x[i];
 }
 return result;
}
var nums = [2, 5, 5];
var result = add.apply(void 0, nums); //12

Function Overloads

In TypeScript, Function overload is purely a compile-time process. It has no impact on the compiled JavaScript code.

The parameter list of a function overload cannot have default parameters. But you can define optional parameters using the question mark '? ' in function overloads.

functionoverloads.ts

function add(x: string, y: string, z: string): string;
function add(x: number, y: number, z: number): number;

// implementation signature
function add(x: any, y: any, z: any): any {
 let result: any;
 if (typeof x == "number" && typeof y == "number" && typeof z == "number") {
 result = x + y + z;
 }
 else {
 result = x + y + " " + z;
 }
 return result;
}

let result1 = add(4, 3, 8); // 15
let result2 = add("Gurukul", "sight", "website"); //Gurukulsight website

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

functionoverloads.js

function add(x, y, z) {
 var result;
 if (typeof x == "number" && typeof y == "number" && typeof z == "number") {
 result = x + y + z;
 }
 else {
 result = x + y + " " + z;
 }
 return result;
}
var result1 = add(4, 3, 8); // 15
var result2 = add("Gurukul", "sight", "website"); //Gurukulsight website

Arrow Function

ES6 provides shorthand syntax for defining anonymous functions. Arrow function omits the function keyword and has lexical scoping of this keyword. TypeScript extends arrow function with types parameters.

arrowfunction.ts

//arrow function with typed parameters
let add = (x: number, y: number)=> {
 return x + y;
};

let result = add(2, 3); //5

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

arrowfunction.js

var add = function (x, y) {
 return x + y;
};
var result = add(2, 3);

The arrow function is typically useful for writing callbacks, which often have an undefined or unexpected this. The use of an arrow function causes the callback to have the same this as the surrounding method has. Let’s understand the concept with the following example.

arrowcallback.ts

class Messenger {
 message: string = "Hello Gurukulsight!";
 greetArrow(): void {
 //arrow function as a callback
 setTimeout(() => console.log(this.message), 2000); //contains parent scope 
 }
 greetAnonymous(): void {
 //anonymous function as a callback
 setTimeout(function () {
 console.log(this.message); // doesn’t contain parent scope
 }, 3000);
 }
};

let m1 = new Messenger();
m1.greetArrow(); //Hello Gurukulsight!
m1.greetAnonymous(); //undefined

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

arrowcallback.js

var Messenger = (function () {
 function Messenger() {
 this.message = "Hello Gurukusight!";
 }
 Messenger.prototype.greetArrow = function () {
 var _this = this;
 setTimeout(function () { return console.log(_this.message); }, 2000); 
 };
 Messenger.prototype.greetAnonymous = function () {
 setTimeout(function () {
 console.log(this.message);
 }, 3000);
 };
 return Messenger;
}());

var m1 = new Messenger();
m1.greetArrow();
m1.greetAnonymous();
What do you think?

I hope you will enjoy the Function in TypeScript while developing your web app. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Take our free typescript skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this