Functions in TypeScript
Functions in TypeScript
Section titled “Functions in TypeScript”Function Type Annotations
Section titled “Function Type Annotations”// Parameter types and return typefunction add(a: number, b: number): number { return a + b;}
// Arrow function syntaxconst multiply = (a: number, b: number): number => { return a * b;};
// TypeScript infers return type when possibleconst divide = (a: number, b: number) => a / b;// Inferred return type: numberOptional and Default Parameters
Section titled “Optional and Default Parameters”// Optional parameter (must come after required)function greet(name: string, greeting?: string): string { return `${greeting ?? "Hello"}, ${name}!`;}
// Default parameter valuefunction createUser( name: string, role: string = "user", isActive: boolean = true): User { return { name, role, isActive };}
createUser("Alice"); // role: "user"createUser("Bob", "admin"); // role: "admin"createUser("Charlie", "moderator", false);Rest Parameters
Section titled “Rest Parameters”// Accept any number of argumentsfunction sum(...numbers: number[]): number { return numbers.reduce((acc, n) => acc + n, 0);}
sum(1, 2, 3, 4, 5); // 15
// Mixed rest parametersfunction buildMessage(prefix: string, ...suffixes: string[]): string { return prefix + suffixes.join(" ");}Function Type Expressions
Section titled “Function Type Expressions”// Declare a function typetype GreetFunction = (name: string) => string;type MathOperation = (a: number, b: number) => number;type Callback<T> = (error: Error | null, result?: T) => void;
// Use the function typeconst sayHello: GreetFunction = (name) => `Hello, ${name}`;const add: MathOperation = (a, b) => a + b;
// Function as parameterfunction operate(a: number, b: number, op: MathOperation): number { return op(a, b);}Function Overloads
Section titled “Function Overloads”// Multiple function signaturesfunction processInput(input: string): string;function processInput(input: number): number;function processInput(input: boolean): boolean;
// Implementation signature — must be compatible with all overloadsfunction processInput(input: string | number | boolean): string | number | boolean { if (typeof input === "string") return input.toUpperCase(); if (typeof input === "number") return input * 2; return !input;}
processInput("hello"); // stringprocessInput(42); // numberprocessInput(true); // booleanthis Parameter
Section titled “this Parameter”// Explicitly type 'this'interface Button { text: string; onClick: (this: HTMLElement, event: MouseEvent) => void;}
const button = document.createElement("button");button.addEventListener("click", function(this: HTMLElement) { console.log(this.textContent); // this is typed as HTMLElement});Generator Functions
Section titled “Generator Functions”function* countdown(start: number): Generator<number, void, unknown> { for (let i = start; i >= 0; i--) { yield i; }}
const counter = countdown(3);console.log(counter.next()); // { value: 3, done: false }console.log(counter.next()); // { value: 2, done: false }console.log(counter.next()); // { value: 1, done: false }Real Project Example
Section titled “Real Project Example”// API request function with overloadsasync function fetchData(url: string): Promise<Response>;async function fetchData<T>(url: string, parser: (data: unknown) => T): Promise<T>;async function fetchData<T>( url: string, parser?: (data: unknown) => T): Promise<Response | T> { const response = await fetch(url); const data = await response.json(); return parser ? parser(data) : response;}
// Usageconst response = await fetchData("/api/users"); // Responseconst users = await fetchData("/api/users", (data) => data as User[]); // User[]Common Mistakes
Section titled “Common Mistakes”| Mistake | Fix |
|---|---|
| Not annotating return types | Use explicit return types for complex functions |
Using Function type | Use specific function signatures |
| Forgetting void return | Use void for functions that don’t return |
| Overloading with incompatible types | Implementation must handle all overloads |
Interview Questions
Section titled “Interview Questions”Easy: How do you type a function parameter and return value?
Medium: What are function overloads and when would you use them?
Hard: Explain how the this parameter works in TypeScript functions.