TypeScript any and unknown
The `any` type turns off type checking for a value, letting it be treated as any type at all. It is useful for gradually migrating JavaScript code but should be used sparingly, since it removes TypeScript's safety benefits.
The `unknown` type is a safer alternative: it can also hold any value, but TypeScript forces you to check or narrow its type before you can use it in most operations.
let value: any = 5;
let input: unknown = "hello";The any type
A variable typed `any` can be assigned any value and used in any way without errors, which reintroduces the risks of plain JavaScript.
The unknown type
A variable typed `unknown` must be checked (for example with `typeof`) before you can call methods on it or use it as a specific type, keeping your code safer.
let value: any = 4;
value = "now a string";
value = true;
console.log(value);true`any` allows the variable to change type freely, bypassing type checks.
let input: unknown = "hello";
if (typeof input === "string") {
console.log(input.toUpperCase());
}HELLOTypeScript requires narrowing unknown with a typeof check before calling string methods on it.
Key points
- `any` disables type checking for that value entirely.
- `unknown` can hold any value but must be narrowed before use.
- Prefer `unknown` over `any` for safer code.
- Overusing `any` defeats the purpose of using TypeScript.
