Functions in TypeScript are blocks of reusable code that can accept parameters and return values. They are similar to JavaScript functions but with added type annotations. TypeScript functions can be:
- Named functions: These are defined using the function keyword and have a specific name.
function add(x: number, y: number): number {
return x + y;
}
- Function expressions: These assign a function to a variable, allowing for flexible function creation and passing.
const add = function(x: number, y: number): number {
return x + y;
};
- Arrow functions: These provide a concise syntax for writing function expressions, often used for short, simple functions.
const add = (x: number, y: number): number => x + y;
TypeScript functions can have optional parameters, default parameters, and rest parameters, and support function overloading.