Generic Functions
Generic functions use type parameters to create flexible, reusable functions that work with multiple types.
Generic Functions
Output
Click Run to execute your code
Type Inference: TypeScript can automatically
infer generic types from arguments, so you don't always need to specify them
explicitly.
Multiple Type Parameters
function merge(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
let result = merge({ name: "Alice" }, { age: 25 });
// Type: { name: string } & { age: number }
Common Mistakes
1. Over-Specifying Types
// โ Redundant - TypeScript can infer
let result = map([1, 2], n => n.toString());
// โ Better - let TypeScript infer
let result = map([1, 2], n => n.toString());
2. Not Using Return Type
// โ Loses type information
function wrap(value: T) {
return { data: value }; // Type: { data: T }
}
// โ Explicit return type
function wrap(value: T): { data: T } {
return { data: value };
}
Best Practice: Let TypeScript infer types when
possible. Only specify types explicitly when needed for clarity.
Summary
- Generic functions use type parameters
- TypeScript infers types from arguments
- Multiple type parameters with
<T, U> - Perfect for array operations and transformations
Enjoying these tutorials?