🧾 any vs unknown
Feature |
|
|
|---|---|---|
Type Safety | ❌ No type checking | ✅ Safer, requires type checking |
Use in operations | ✅ Allowed directly | ❌ Not allowed without narrowing |
Flexibility | ✅ Fully flexible | ⚠️ Flexible, but requires checking |
Default behavior | Can lead to runtime errors | Helps prevent unsafe operations |
✅ Use any When:
You are gradually migrating JavaScript to TypeScript and don’t know the type yet.
You are dealing with 3rd party libraries that lack proper type definitions.
You want to bypass TypeScript’s type system temporarily (not recommended in production).
Example:
let value: any = "Hello";
value.toUpperCase(); // No error, but could be risky if value is not a string✅ Use unknown When:
You want a type-safe alternative to
any.You're handling dynamic input (e.g., from JSON, APIs, user input).
You want to force the developer to do type checking or type narrowing before use.
Example:
let value: unknown = "Hello";
// value.toUpperCase(); ❌ Error
if (typeof value === "string") {
console.log(value.toUpperCase()); ✅
}🧠 Summary
Scenario | Use |
|---|---|
Not sure about the type (temporary) |
|
Input from external or dynamic source |
|
You want full flexibility (risky) |
|
You want flexibility with safety |
|
🟡 Pro Tip: Avoid any in production code. Prefer unknown with proper checks to keep the benefits of TypeScript’s type safety.
Let me know if you'd like real-world examples (e.g., API handling, form validation, etc.) using unknown.