How do generics differ from any?
1. The main difference
| Feature | any | generics |
|---|---|---|
| Typing | Turns off type checking | Preserves type information |
| Safety | Loss of type safety | Full type safety |
| Type substitution | The type is unknown | The type is substituted automatically |
| Purpose | Quickly "silence" a type error | Build a universal and type-safe function/type |
2. An example with any
javascript
function identity(value: any): any {
return value;
}
const result = identity("Hello");
result.toFixed(); // The error only shows up at runtimeTypeScript does not know that result is a string, and happily allows calling toFixed(), which leads to an error at runtime.
3. An example with generics
javascript
function identity<T>(value: T): T {
return value;
}
const result = identity("Hello");
result.toUpperCase(); // Everything is correct
result.toFixed(); // A compile-time errorT preserves the type information (string), and TypeScript knows which methods are available.
4. Generics are "flexible" but typed
javascript
function merge<T, U>(a: T, b: U): T & U {
return Object.assign({}, a, b);
}
const person = merge({ name: "Tim" }, { age: 25 });
// person has the type { name: string; age: number }With any, TypeScript could not infer the exact type of the merged object.
5. Why any is dangerous
javascript
let value: any = 5;
value = "text";
value = true;
value.push(1); // The error only appears at runtimeany breaks all typing guarantees, TypeScript stops helping you.
6. When to use which
| When to use | Why |
|---|---|
generics | When you want flexibility and type safety (libraries, utilities, React hooks, etc.) |
any | Only as a temporary solution during migration or complex typing |
Summary
anyis a typing "off switch".genericsis a "smart abstraction" that adapts to types but does not lose them.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.