Introduction
In this chapter, we will explore functions in TypeScript. Functions are fundamental building blocks in TypeScript and JavaScript, allowing you to encapsulate reusable code blocks. Understanding how to define and use functions effectively is essential for writing modular and maintainable TypeScript programs.
Table of Contents
- Definition
- Function Syntax
- Named Functions
- Anonymous Functions
- Arrow Functions
- Function Parameters
- Optional and Default Parameters
- Rest Parameters
- Function Overloads
- Complete Example with Output
- Conclusion
Definition
A function in TypeScript is a block of code designed to perform a particular task. Functions are executed when they are called (invoked). You can pass data, known as parameters, into a function and return data from it.
Function Syntax
Syntax
function functionName(parameters: type): returnType {
// code to be executed
}
Example
This example demonstrates a simple function that adds two numbers and returns the result.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 3)); // Output: 8
Output
8
Named Functions
Named functions are defined using the function
keyword followed by the function name.
Example
This example defines a named function that multiplies two numbers.
function multiply(a: number, b: number): number {
return a * b;
}
console.log(multiply(4, 5)); // Output: 20
Output
20
Anonymous Functions
Anonymous functions are functions without a name, often used as arguments to other functions or assigned to variables.
Example
This example assigns an anonymous function to a variable and calls it.
let subtract = function(a: number, b: number): number {
return a - b;
};
console.log(subtract(10, 3)); // Output: 7
Output
7
Arrow Functions
Arrow functions provide a more concise syntax for writing functions and do not have their own this
context.
Example
This example uses an arrow function to divide two numbers.
let divide = (a: number, b: number): number => {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
Output
5
Function Parameters
Functions can have parameters to accept inputs. These parameters must have specified types in TypeScript.
Example
This example demonstrates a function with parameters.
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ramesh")); // Output: Hello, Ramesh!
Output
Hello, Ramesh!
Optional and Default Parameters
Parameters can be marked as optional using ?
or have default values.
Example
This example demonstrates optional and default parameters.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Ramesh")); // Output: Hello, Ramesh!
console.log(greet("Suresh", "Hi")); // Output: Hi, Suresh!
Output
Hello, Ramesh!
Hi, Suresh!
Rest Parameters
Rest parameters allow you to pass an arbitrary number of arguments to a function, which are collected into an array.
Example
This example uses rest parameters to sum an arbitrary number of values.
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
Output
6
22
Function Overloads
Function overloads allow you to define multiple signatures for a function, providing different ways to call it.
Example
This example demonstrates function overloads for a function that combines values.
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any): any {
return a + b;
}
console.log(combine(1, 2)); // Output: 3
console.log(combine("Hello, ", "TypeScript!")); // Output: Hello, TypeScript!
Output
3
Hello, TypeScript!
Complete Example with Output
In this section, we will combine the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.
TypeScript Code
You can test the following code in the TypeScript Playground.
// Named Function
function multiply(a: number, b: number): number {
return a * b;
}
console.log(multiply(4, 5)); // Output: 20
// Anonymous Function
let subtract = function(a: number, b: number): number {
return a - b;
};
console.log(subtract(10, 3)); // Output: 7
// Arrow Function
let divide = (a: number, b: number): number => {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
// Function with Parameters
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ramesh")); // Output: Hello, Ramesh!
// Optional and Default Parameters
function greetWithDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greetWithDefault("Ramesh")); // Output: Hello, Ramesh!
console.log(greetWithDefault("Suresh", "Hi")); // Output: Hi, Suresh!
// Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
// Function Overloads
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any): any {
return a + b;
}
console.log(combine(1, 2)); // Output: 3
console.log(combine("Hello, ", "TypeScript!")); // Output: Hello, TypeScript!
Conclusion
In this chapter, we covered functions in TypeScript, including named functions, anonymous functions, arrow functions, function parameters, optional and default parameters, rest parameters, and function overloads. We provided a complete example with its output to illustrate how these functions work in TypeScript. Understanding functions is essential for writing modular and maintainable TypeScript programs.
Comments
Post a Comment
Leave Comment