Generics Introduction
Generics allow you to write reusable code that works with multiple types while maintaining type safety.
What Are Generics?
Output
Click Run to execute your code
Generic Syntax: Use angle brackets
<T> to define type parameters. T is a
placeholder for any type.Why Use Generics?
- Reusability: Write once, use with any type
- Type safety: Catch errors at compile-time
- No type casting: TypeScript infers types
- Better IDE support: Autocomplete works perfectly
Generics vs Any
| Feature | Generics | Any |
|---|---|---|
| Type safety | ✓ Full type checking | ✗ No type checking |
| Autocomplete | ✓ Works perfectly | ✗ No autocomplete |
| Refactoring | ✓ Safe refactoring | ✗ Unsafe |
| Return type | ✓ Preserves type | ✗ Returns any |
Common Mistakes
1. Using Any Instead of Generics
// ✗ Wrong - loses type safety
function identity(value: any): any {
return value;
}
// ✓ Correct - maintains type safety
function identity(value: T): T {
return value;
}
2. Not Specifying Type Parameters
// Works but less explicit
let result = identity(42); // Type inferred
// ✓ Better - explicit type
let result = identity(42);
Best Practice: Use generics when you need
type-safe reusable code. Common naming:
T (Type), K
(Key), V (Value).Summary
- Generics enable reusable, type-safe code
- Use
<T>syntax for type parameters - Better than
any- preserves type information - TypeScript can infer generic types
Enjoying these tutorials?