4 min read
•Question 27 of 48easyWhat is the difference between unknown and any?
Type-safe alternative to any.
What You'll Learn
- any type
- unknown type
- When to use each
any Type
Disables type checking entirely.
code.tsTypeScript
let value: any = "hello";
// No errors, but dangerous!
value.foo.bar.baz;
value();
value.toUpperCase();
value = 42;unknown Type
Type-safe counterpart to any. Requires type checking before use.
code.tsTypeScript
let value: unknown = "hello";
// Errors! Must check type first
value.toUpperCase(); // Error
value.foo; // Error
// After type checking, OK
if (typeof value === "string") {
value.toUpperCase(); // OK
}Comparison
| Feature | any | unknown |
|---|---|---|
| Assignable to | Everything | Only unknown/any |
| Operations | All allowed | Must narrow first |
| Type safety | None | Preserved |
When to Use
code.tsTypeScript
// Use unknown for values from external sources
async function fetchData(): Promise<unknown> {
const response = await fetch("/api");
return response.json();
}
// Use any only when migrating JS or with problematic libs
declare const legacyLib: any;