Skip to main content

How do generics differ from any?

1. The main difference

Featureanygenerics
TypingTurns off type checkingPreserves type information
SafetyLoss of type safetyFull type safety
Type substitutionThe type is unknownThe type is substituted automatically
PurposeQuickly "silence" a type errorBuild 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 runtime

TypeScript 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 error

T 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 runtime

any breaks all typing guarantees, TypeScript stops helping you.


6. When to use which

When to useWhy
genericsWhen you want flexibility and type safety (libraries, utilities, React hooks, etc.)
anyOnly as a temporary solution during migration or complex typing

Summary

any is a typing "off switch". generics is a "smart abstraction" that adapts to types but does not lose them.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.