Loading lessons...
Special Types: any, unknown & never
Special Types: any, unknown, and never
TypeScript includes special escape hatch and type-safety types to handle dynamic data or impossible control flows.
Summary of Special Types
| Type | Safety Level | Usage |
|---|---|---|
any | Unsafe | Opts out of all type checking. Avoid in production. |
unknown | Type-safe | Top type for values of uncertain type. Requires type narrowing before use. |
never | Bottom type | Represents values that NEVER occur (e.g. functions throwing errors or infinite loops). |
Comparison Code Examples
Using any (DANGEROUS):
let data: any = "hello";
data.nonExistentMethod(); // Compiles fine, crashes at runtime!
Using unknown (SAFE):
let value: unknown = "hello";
// value.toUpperCase(); // Error: Object is of type 'unknown'.
if (typeof value === "string") {
console.log(value.toUpperCase()); // Safe! Type narrowed to string.
}
Using never (Exhaustiveness checking):
function throwError(msg: string): never {
throw new Error(msg);
}
TL;DR
- Prefer
unknownoveranywhen dealing with external API responses or dynamic inputs. unknownforces you to perform type checking/narrowing before calling methods on it.neverensures exhaustive switch statements and represents impossible values.