Suggest an editImprove this articleRefine the answer for “How do generics differ from any?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`any`** turns off type checking and completely loses type safety, while **generics** (`<T>`) preserve type information and substitute it automatically, keeping full type safety. **Key point:** generics give flexibility without losing type checking (for example, an incorrect method call is caught at compile time), whereas with `any` the same mistake only shows up at runtime.Shown above the full answer for quick recall.Answer (EN)Image### 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 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 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 > `any` is a typing "off switch". > `generics` is a "smart abstraction" that **adapts to types** but **does not lose** them.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.