Function Type Annotations
Function Type Annotations
Basic Function Types
// Function declaration
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const multiply = (a: number, b: number): number => a * b;
// Function type
const divide: (a: number, b: number) => number = (a, b) => a / b;
Void Return Type
function log(message: string): void {
console.log(message);
}
// void means function doesn't return anything
// You can return undefined, but not a value
function noop(): void {
return undefined; // OK
// return 42; // Error!
}
Never Return Type
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}
Function Type Aliases
type Callback = (data: string) => void;
type Predicate<T> = (item: T) => boolean;
type Mapper<T, U> = (item: T) => U;
function process(items: string[], callback: Callback): void {
items.forEach(callback);
}
const numbers = [1, 2, 3];
const isEven: Predicate<number> = (n) => n % 2 === 0;
const doubled: Mapper<number, string> = (n) => String(n * 2);
Optional Parameters
Optional Parameters
Optional Parameters
Use ? for parameters that can be omitted:
function greet(name: string, greeting?: string): string {
return `${greeting || "Hello"}, ${name}!`;
}
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"
Default Parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"
Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15
// With other parameters
function log(level: string, ...messages: string[]): void {
console.log(`[${level}]`, ...messages);
}
log("INFO", "Server started", "on port 3000");
Parameter Ordering
// Required must come before optional
function createUser(
name: string, // required
age: number, // required
email?: string // optional
) {}
// Default can go anywhere (but usually last)
function config(
host: string = "localhost",
port: number,
debug: boolean = false
) {}
config("example.com", 8080); // uses defaults
Function Overloads
Function Overloads
Function overloads allow a function to have multiple signatures.
Basic Overloads
function format(input: string): string;
function format(input: number): string;
function format(input: Date): string;
function format(input: string | number | Date): string {
if (typeof input === "string") {
return input.toUpperCase();
} else if (typeof input === "number") {
return input.toFixed(2);
} else {
return input.toISOString();
}
}
format("hello"); // "HELLO"
format(3.14159); // "3.14"
format(new Date()); // ISO string
Overloads with Different Returns
function createElement(tag: "div"): HTMLDivElement;
function createElement(tag: "span"): HTMLSpanElement;
function createElement(tag: string): HTMLElement;
function createElement(tag: string): HTMLElement {
return document.createElement(tag);
}
const div = createElement("div"); // HTMLDivElement
const span = createElement("span"); // HTMLSpanElement
Overloads vs Union Types
// Union type (simpler)
function process(input: string | number): string {
return String(input);
}
// Overload (more precise)
function process(input: string): string;
function process(input: number): string;
function process(input: string | number): string {
return String(input);
}
// Overload gives more specific return types
function getLength(input: string): number;
function getLength(input: Array<any>): number;
function getLength(input: string | Array<any>): number {
return input.length;
}
Practice Problems
Create a reusable React component implementing Function Types. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Function Types using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Function Types for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the return type for a function that doesn't return a value?
2. How do you make a function parameter optional?
3. What is the difference between void and never?
4. When should you use function overloads?
Flashcards
Question
How do you type a function parameter?
Click to reveal answer
Answer
param: type, e.g., name: string
Question
How do you type a function return value?
Click to reveal answer
Answer
Add : type after parameters, e.g., (): number
Question
What is a rest parameter?
Click to reveal answer
Answer
...args: type[] for variable number of arguments
Question
What are function overloads?
Click to reveal answer
Answer
Multiple signatures for a single function implementation
Question
What is Function Types?
Click to reveal answer
Answer
Function Types is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Use void for functions that don't return values
- 2.Use never for functions that never return
- 3.Optional parameters use ? and must come after required
- 4.Default parameters use = and can go anywhere
- 5.Function overloads provide multiple signatures
Interview Tips
- •Explain the difference between void and never
- •Know when to use optional vs default parameters
- •Understand when function overloads are useful
Cheat Sheet
Cheat Sheet
Basic Function Types
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
Optional & Default
function greet(name: string, greeting?: string) {}
function greet(name: string, greeting = "Hello") {}
Rest Parameters
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
Function Types
type Callback = (data: string) => void;
type Predicate<T> = (item: T) => boolean;
Overloads
function format(input: string): string;
function format(input: number): string;
function format(input: string | number): string { ... }