In TypeScript, declaring a function can be achieved in several ways, such as Function Declarations, Function Expressions, and Arrow Functions. When declaring functions in TypeScript, you can specify parameter types and return types, which enhances code readability and maintainability. Below, I'll demonstrate these different methods with examples.
1. Function Declarations
This is the most fundamental approach to declaring functions. In TypeScript, you can define types for both parameters and return values.
typescriptfunction add(x: number, y: number): number { return x + y; } console.log(add(1, 2)); // Output: 3
In this example, the add function accepts two parameters x and y of type number and returns a result of type number.
2. Function Expressions
Functions can also be declared as expressions, allowing you to specify parameter types and return types.
typescriptconst multiply = function(x: number, y: number): number { return x * y; }; console.log(multiply(3, 4)); // Output: 12
Here, multiply is a function expression that accepts two number parameters and returns their product.
3. Arrow Functions
Arrow functions offer a more concise syntax for function expressions while preserving the ability to specify types.
typescriptconst subtract = (x: number, y: number): number => { return x - y; }; console.log(subtract(10, 5)); // Output: 5
In this example, subtract is an arrow function that calculates the difference between two numbers.
4. Optional Parameters and Default Parameters
TypeScript supports optional parameters and default parameters, which can be defined during function declaration.
typescriptfunction greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`; } console.log(greet("Alice")); // Output: "Hello, Alice!" console.log(greet("Bob", "Hi")); // Output: "Hi, Bob!"
Here, the greet function includes a default parameter greeting. If this parameter is omitted during the call, it defaults to "Hello".
These are the common approaches to declaring functions in TypeScript. By specifying types, function declarations not only improve code clarity and maintainability but also provide real-time type checking during development, reducing runtime errors.