TypeScript introduces special top and bottom types—any, unknown, never, void, undefined, and null—to model unconstrained, unsafe, impossible, or missing values.
flowchart TD
A["Top Types (Can accept any value)"] --> B["any (Unsafe - Disables checking)"]
A --> C["unknown (Safe - Requires type guard)"]
D["Bottom Type (Can never occur)"] --> E["never (Empty set / Unreachable code)"]
F["Absence of Value"] --> G["void (Function returns no value)"]
F --> H["null & undefined (Strict missing values)"]
// unknown: Safe dynamic type requiring narrowing
function parseApiResponse(jsonString: string): unknown {
return JSON.parse(jsonString);
}
const rawData = parseApiResponse('{"userId": 42, "username": "alex"}');
// Must narrow unknown before accessing properties
if (typeof rawData === "object" && rawData !== null && "username" in rawData) {
console.log(`Username: ${(rawData as { username: string }).username}`);
}
// never: Exhaustiveness checking in switch statements
type SystemEvent = { type: "login" } | { type: "logout" };
function handleEvent(event: SystemEvent): void {
switch (event.type) {
case "login":
console.log("User logged in");
break;
case "logout":
console.log("User logged out");
break;
default:
// Compiler error if a new event type is added without a case!
const _exhaustiveCheck: never = event;
throw new Error(`Unhandled event: ${_exhaustiveCheck}`);
}
}
unknown Over any: unknown forces you to validate data before using it, preserving type safety.never for Exhaustive Switch Checks: Catch missing enum or union branches at compile time.strictNullChecks: Ensures null and undefined cannot be silently assigned to primitive types without explicit union annotations (string | null).Create a variable of type unknown, assign "Hello TypeScript" to it, and attempt to call .toUpperCase() directly. What compiler error do you receive?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With