Functions are first-class citizens, and you can define types for functions to provide clear interfaces and enforce type safety. Here's an overview of how functions and types are used together in TypeScript:
- 1. Function Declarations:
- 2. Function Expressions:
- 3. Function Types:
- 4. Optional and Default Parameters:
- 5. Rest Parameters:
- 6. Function Types as Parameters:
- 7. Generic Functions:
- 8. Function Overloads:
- 9. Callbacks:
You can declare functions with type annotations for parameters and return types:
function add(a: number, b: number): number {
return a + b;
}
In this example, the add
function takes two parameters (a
and b
) of type number
and returns a value of type number
.
Functions can also be assigned to variables and used as expressions:
const subtract: (a: number, b: number) => number = function (a, b) {
return a - b;
};
Here, the subtract
variable is assigned a function expression with a specified type for parameters and return value.
You can define function types separately using the type
keyword:
type MathOperation = (a: number, b: number) => number;
Now, you can use this type to declare functions or variables:
const multiply: MathOperation = (a, b) => a * b;
Function types can include optional and default parameters:
type PrintMessageFunction = (message: string, urgency?: boolean) => void;
const printMessage: PrintMessageFunction = (message, urgency = false) => {
console.log(urgency ? `URGENT: ${message}` : message);
};
Function types can also include rest parameters:
type SumFunction = (...numbers: number[]) => number;
const sum: SumFunction = (...numbers) => numbers.reduce((acc, num) => acc + num, 0);
You can use function types as parameters:
type OperationFunction = (a: number, b: number) => number;
function performOperation(operation: OperationFunction, a: number, b: number): number {
return operation(a, b);
}
You can create generic functions that work with different types:
function identity<T>(value: T): T {
return value;
}
Here, T
is a generic type parameter.
You can use function overloads to specify multiple signatures for a function:
function greet(name: string): string;
function greet(name: string, age: number): string;
function greet(name: string, age?: number): string {
if (age !== undefined) {
return `Hello, ${name}! You are ${age} years old.`;
} else {
return `Hello, ${name}!`;
}
}
Function types are commonly used with callbacks:
type CallbackFunction = (result: number) => void;
function performOperation(a: number, b: number, callback: CallbackFunction): void {
const result = a + b;
callback(result);
}
By using function types and types for function parameters, TypeScript helps catch errors during development and provides clear interfaces for functions, contributing to code safety and readability.