Day 42: Typed Functions
Dharan Ganesan
Posted on September 6, 2023
Defining Functions
In TypeScript, you can define functions using the function
keyword or as arrow functions (=>
). Let's start with the traditional function definition:
function greet(name: string): string {
return `Hello, ${name}! 👋`;
}
And here's an arrow function equivalent:
const greet = (name: string): string => `Hello, ${name}! 👋`;
Optional and Default Parameters
In TypeScript, you can make function parameters optional by adding a ?
after their name. You can also provide default values:
function welcome(name: string = "User", age?: number): string {
if (age) {
return `Welcome, ${name}! You are ${age} years old. 🎉`;
} else {
return `Welcome, ${name}! 🎉`;
}
}
Here, the name
parameter is optional, and if age
is not provided, it defaults to undefined
.
Rest Parameters
If you want to pass an arbitrary number of arguments to a function, you can use rest parameters:
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
const result = sum(1, 2, 3, 4, 5); // result is 15
The ...numbers
syntax allows you to pass any number of arguments, which are then treated as an array within the function.
Function Overloading
TypeScript allows you to define multiple function signatures for the same function name, known as function overloading:
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
return a + b;
}
const result1 = combine("Hello, ", "TypeScript!"); // result1 is a string
const result2 = combine(5, 10); // result2 is a number
Depending on the arguments provided, TypeScript will select the appropriate function signature.
Higher-Order Functions
You can also create higher-order functions that take functions as parameters or return functions:
function apply(func: (x: number) => number, value: number): number {
return func(value);
}
const square = (x: number) => x * x;
const result = apply(square, 5); // result is 25
Posted on September 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.