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?