Functions in TypeScript
Functions are fundamental building blocks in TypeScript. They allow you to encapsulate code for reuse, define the behavior of your application, and ensure type safety through TypeScript’s type annotations.
Function Basics
A function in TypeScript can be defined using the function
keyword followed by the function name, parameters, and return type. Here’s a basic example:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
Optional Parameters and Default Values
TypeScript allows you to define optional parameters and default values for parameters:
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Bob")); // Output: Hello, Bob!
console.log(greet("Charlie", "Hi")); // Output: Hi, Charlie!
Rest Parameters
Rest parameters allow you to pass an arbitrary number of arguments to a function:
function add(...numbers: number[]): number {
return numbers.reduce((sum, current) => sum + current, 0);
}
console.log(add(1, 2, 3, 4, 5)); // Output: 15
Function Types
In TypeScript, you can define the type of a function, which includes the types of its parameters and return value:
let myFunction: (a: number, b: number) => number;
myFunction = (x, y) => x + y;
console.log(myFunction(10, 20)); // Output: 30
Anonymous Functions and Arrow Functions
Anonymous functions (functions without a name) and arrow functions provide a concise way to write function expressions:
let multiply = (x: number, y: number): number => {
return x * y;
};
console.log(multiply(5, 4)); // Output: 20
Function Overloading
TypeScript allows you to define multiple signatures for a single function, enabling function overloading:
function double(value: number): number;
function double(value: string): string;
function double(value: any): any {
if (typeof value === "number") {
return value * 2;
} else if (typeof value === "string") {
return value + value;
}
}
console.log(double(10)); // Output: 20
console.log(double("Hello")); // Output: HelloHello
Callback Functions
Callback functions are functions passed as arguments to other functions. They are often used for asynchronous operations:
function fetchData(callback: (data: string) => void) {
setTimeout(() => {
callback("Fetched data");
}, 1000);
}
fetchData((data) => {
console.log(data); // Output after 1 second: Fetched data
});
Conclusion
Functions in TypeScript are versatile and powerful, offering a variety of features to handle different use cases. Understanding how to define, use, and type functions effectively is crucial for writing clean, maintainable, and type-safe code. Whether you are using basic functions, working with optional and rest parameters, or leveraging advanced features like function overloading and callbacks, TypeScript provides robust support for functional programming.
Comments
Post a Comment