Functions are the building blocks of any application. TypeScript adds type safety to parameters, return values, and function expressions. **Key Concepts:** • Parameter & return types • Optional/default parameters • Rest parameters • Function overloads • Arrow functions vs declarations Typed functions catch errors early, document expectations, and improve IDE help.
function name(param: Type): ReturnType { ... }// BASIC FUNCTION
function greet(name: string): string {
return `Hello, ${name}!`;
}
// OPTIONAL + DEFAULT
function buildUser(name: string, age?: number, active: boolean = true) {
return { name, age, active };
}
// REST
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
// FUNCTION TYPE ALIAS
type MathOp = (a: number, b: number) => number;
const add: MathOp = (a, b) => a + b;
// OVERLOAD (compile-time signatures)
function format(value: string): string;
function format(value: number): string;
function format(value: string | number) {
return value.toString();
}
// ARROW VS FUNCTION FOR 'this'
const counter = {
count: 0,
inc() {
this.count += 1; // ok, has 'this'
},
};Understanding Functions & Signatures is fundamental to mastering TypeScript. Practice with the examples above and experiment with variations to solidify your knowledge.