Functions: are the primary means of passing data around in JavaScript. TypeScript allows you to specify the types of both the input and output values of functions.
enabling better type checking and code clarity.
Function Declaration: You can declare a function using the function
keyword. You can specify parameter types and the return type using type annotations.
function add(a: number, b: number): number {
return a + b;
}
Parameter Type Annotations:
When you declare a function, you can add type annotations
after each parameter to declare what types of parameters the function
accepts. Parameter type annotations go after the parameter
name:
function greet(name: string)
{
console.log(“Hello, ” +
name.toUpperCase() + “!!”);
}
Optional Parameters: You can make function parameters optional by adding a ?
after the parameter name. Optional parameters must be placed at the end of the parameter list.
function greet(name: string, age?: number): string {
if (age) {
return Hello, ${name}! You are ${age} years old.;
} else {
return Hello, ${name}!;
}
}
Default Parameters: You can assign default values to function parameters using the =
symbol.
function greetDefault(name: string, greeting: string = "Hello"): string {
return ${greeting}, ${name}!;
}
Function Types: You can define the type of a function using the arrow =>
notation. This is particularly useful when you want to declare function types for variables or interfaces.
type MathOperation = (a: number, b: number) => number;
const subtract: MathOperation = (a, b) => a - b;
Anonymous Functions and Lambdas: TypeScript supports anonymous functions and lambda expressions.
const multiply = function(x: number, y: number): number { return x * y; }
;const power = (base: number, exponent: number): number => base ** exponent;
Function Overloading: TypeScript allows you to provide multiple type signatures for a single function using function overloading.function formatOutput(value: string): string; function formatOutput(value: number): string; function formatOutput(value: any): string { return `Value: ${value}`; }
Higher-Order Functions: TypeScript supports higher-order functions, which are functions that take other functions as parameters or return functions.function applyOperation(x: number, y: number, operation: MathOperation): number { return operation(x, y); }