How To Use Functions in TypeScript

TypeScript functions are your trusty workhorses in any program. They encapsulate reusable code blocks, helping you organize your logic, improve modularity, and avoid code duplication.

Function Declaration

The basic syntax for declaring a function in TypeScript is as follows.

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

In this example, the add function takes two parameters (x and y) of type number and returns a result of type number.

Function Expression

Functions can also be assigned to variables. This is known as a function expression:

let multiply = function (x: number, y: number): number { return x * y; };

Here, the multiply variable is assigned a function that multiplies two numbers.

Let's explore deeper into their details with some examples:

function sum(a: number, b: number): number { return a + b; } const result = sum(5, 10); console.log(result); // Output: 15

This defines a function sum that takes two numbers as parameters (typed as number) and returns their sum as a number. It demonstrates basic function creation, parameter typing, and return values.

Function with Default Parameters

function greet(name: string = "Guest"): string { return `Hello, ${name}!`; } console.log(greet()); // Output: "Hello, Guest!" console.log(greet("John")); // Output: "Hello, John!"

This function introduces optional parameters with default values. Here, name has a default value of "Guest", allowing you to call the function without explicitly providing a name. This provides flexibility and improves code readability.

Function Overloading

function multiply(a: number, b: number): number; function multiply(a: string, b: number): string; function multiply(a: any, b: number): any { if (typeof a === "number") { return a * b; } else { return a.repeat(b); } } console.log(multiply(5, 2)); // Output: 10 console.log(multiply("*", 3)); // Output: ***

This example showcases function overloading, allowing you to define the same function name with different parameter types and functionalities. This offers flexibility when your function handles different data types but performs similar tasks.

Arrow Functions

const getName = (): string => "TypeScript"; const addNumbers = (a: number, b: number) => a + b; console.log(getName()); // Output: "TypeScript" console.log(addNumbers(3, 7)); // Output: 10

Arrow functions provide a concise syntax for declaring anonymous functions. They're often used for short, single-line expressions, improving code readability and conciseness.

Function as First-Class Citizens

const functions = { sum: function (a: number, b: number): number { return a + b; }, multiply: (a: number, b: number) => a * b, }; console.log(functions.sum(2, 4)); // Output: 6 console.log(functions.multiply(5, 3)); // Output: 15

Functions can be assigned to variables, passed as arguments, and returned from other functions. This makes them first-class citizens in TypeScript, offering powerful abstraction and flexibility for building modular and reusable code.

Rest Parameters

Functions can accept a variable number of arguments using rest parameters:

function concatenateStrings(...args: string[]): string { return args.join(' '); }

The concatenateStrings function takes any number of string arguments and joins them into a single string.

Generic Functions

TypeScript supports generic functions for creating reusable, type-safe functions:

function identity<T>(arg: T): T { return arg; }

The identity function can be used with any type, preserving the input type for the output.

Function Type

Functions in TypeScript have types, and you can explicitly specify the function type:

let myFunction: (x: number, y: number) => number = function (x, y) { return x + y; };

Here, myFunction is explicitly typed to accept two numbers and return a number.

Conclusion

Functions are declared using the function keyword and can be assigned to variables or written as concise arrow functions. They support features such as optional and default parameters, rest parameters, function overloading, generics, and explicit typing, making them versatile tools for structuring and reusing code. Functions in TypeScript play a crucial role in encapsulating logic, promoting code organization, and enhancing type safety.