TypeScript enhances JavaScript functions with strong typing, better inference, and advanced features, making code safer, more readable, and more scalable. Understanding its function-related capabilities can greatly improve development efficiency.
1. TypeScript Infers Function Argument Types
TypeScript can automatically guess the types of function arguments based on how they are used, especially in callbacks.
const numbers = [1, 2, 3];
numbers.forEach((num) => console.log(num.toFixed(2))); // TypeScript infers `num` as a number
2. Typing this in Callback Functions
You can specify the type of this in callback functions to ensure it behaves as expected.
interface Button {
onClick: (this: Button, event: Event) => void;
}
const button: Button = {
onClick() {
console.log(`Button clicked: ${this}`); // `this` is correctly typed as `Button`
},
};
3. Function Overloading with Different Return Types
TypeScript allows you to define multiple function signatures with different return types based on input types.
function parseInput(input: string): string;
function parseInput(input: number): number;
function parseInput(input: string | number): string | number {
if (typeof input === "string") {
return `Parsed string: ${input}`;
} else {
return input * 2; // Return a number
}
}
console.log(parseInput("Hello")); // Parsed string: Hello
console.log(parseInput(10)); // 20
4. Strongly Typed Rest Parameters
Rest parameters can be typed as tuples to enforce a specific structure.
function logDetails(...details: [string, number]): void {
console.log(`Name: ${details[0]}, Age: ${details[1]}`);
}
logDetails("Alice", 25); // Name: Alice, Age: 25
5. Functions Can Return Different Types
TypeScript functions can return different types based on the input.
function process(value: string | number) {
return typeof value === "string" ? value.toUpperCase() : value * 2;
}
console.log(process("hello")); // "HELLO"
console.log(process(5)); // 10
6. Function Currying in TypeScript
Currying allows you to create reusable functions by returning another function.
function add(a: number): (b: number) => number {
return (b: number) => a + b;
}
const addFive = add(5);
console.log(addFive(10)); // 15
7. Function Types for Callbacks
You can define function types for callbacks to improve readability.
type ClickHandler = (event: MouseEvent) => void;
const handleClick: ClickHandler = (event) => {
console.log(event.clientX, event.clientY);
};
document.addEventListener("click", handleClick);
8. Generic Functions with Constraints
Generic functions can enforce constraints to ensure the input meets specific conditions.
function logLength<T extends { length: number }>(arg: T): void {
console.log(arg.length);
}
logLength("Hello"); // 5
logLength([1, 2, 3]); // 3
9. Using void as a Return Type
The void return type indicates that a function does not return a value.
function logMessage(message: string): void {
console.log(message);
// No return statement is needed
}
logMessage("Hello, TypeScript!");