TypeScript: any vs unknown vs never Explained
Understanding these special types is crucial for type-safe TypeScript code.
The any Type
any disables all type checking. Avoid using it in new code.
let value: any;
value = 42;
value = "hello";
value.toUpperCase(); // No error at compile timeThe unknown Type
unknown is type-safe. You must check the type before using it.
let value: unknown;
value = 42;
// Must check type first
if (typeof value === "string") {
console.log(value.toUpperCase()); // Safe!
}Real-World Example:
async function fetchUser(id: string) {
const response = await fetch(`/api/users/${id}`);
const data: unknown = await response.json();
if (isUser(data)) {
return data;
}
throw new Error("Invalid data");
}
function isUser(obj: unknown): obj is User {
return typeof obj === "object" && obj !== null && "id" in obj;
}The never Type
never represents values that never occur. Used for exhaustive checking.
function throwError(message: string): never {
throw new Error(message);
}
// Exhaustive check example
type Shape = { kind: "circle" } | { kind: "square" };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 0;
case "square":
return 0;
default:
const _exhaustive: never = shape;
throw new Error("Unhandled shape");
}
}Comparison
| Type | Assign To | Assign From | Use Case | | ----------- | ------------ | ----------- | ----------------- | | any | Everything | Everything | Migration only | | unknown | any, unknown | Everything | External data | | never | Nothing | Nothing | Impossible states |
Best Practices
1. Never use any in new code 2. Always use unknown for dynamic data 3. Use never for exhaustive type checking 4. Always validate unknown values with type guards
Your code will be safer and more maintainable!
Topic Hub
Frontend Architecture / Tooling
Architecture, platform choices, and AI-assisted development workflows.
Open Frontend Architecture / Tooling hubRelated Reading
14 min read
Serverless & Edge Architecture for Full-Stack Apps
Master serverless and edge computing patterns for building scalable, cost-effective full-stack applications. Learn when to use each approach and how to implement them.
12 min read
AI-Assisted Development Tools Every Web Developer Should Use in 2025
Discover the AI-powered tools transforming web development workflows, from code generation to design-to-code, and how to integrate them effectively.
Need a frontend roadmap that supports growth, not churn?
I help product and marketing teams simplify stack decisions, reduce frontend drag, and ship faster without creating long-term maintenance debt.
Written by Salman Izhar
Frontend Developer specializing in React, Next.js, and building high-converting web applications.
Learn More