any and unknown
Escape hatches for values whose type you don't know — and why unknown is safer.
Syntax
let a: any;
let u: unknown;Sometimes you don't know a value's type ahead of time.
any
any turns off type checking for that value. It is flexible but dangerous because mistakes slip through.
unknown
unknown also accepts any value, but TypeScript forces you to check the type before you use it. This makes unknown the safer choice.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A migration from JavaScript uses any temporarily to silence errors while adding proper types file by file.
- An API client types a raw JSON response as unknown and validates it before passing data into typed functions.
- A generic serializer accepts unknown input and narrows it via type guards before processing.
More examples
any bypasses type checking
Demonstrates that any disables all type checking, allowing any operation without compiler complaints.
let data: any = 'hello';
data = 42; // no error
data = { key: true }; // no error
data.foo.bar(); // no compile error — but may crash at runtimeunknown requires narrowing first
Shows that unknown forces you to narrow the type before performing operations, making it safer than any.
function process(value: unknown): string {
if (typeof value === 'string') {
return value.toUpperCase(); // safe: narrowed to string
}
return String(value); // fallback conversion
}Typing an API response as unknown
Illustrates a realistic pattern where an HTTP response is typed as unknown and narrowed before accessing properties.
async function fetchUser(id: number): Promise<unknown> {
const res = await fetch(`/api/users/${id}`);
return res.json(); // typed as unknown
}
async function main() {
const raw = await fetchUser(1);
if (typeof raw === 'object' && raw !== null && 'name' in raw) {
console.log((raw as { name: string }).name);
}
}
Discussion