Q05. What is the difference between any and unknown?
any disables most checking for a value. unknown can hold any value but requires narrowing before unsafe operations. Prefer unknown at untrusted boundaries and validate it into a known domain type.
With unknown, accessing .name directly is rejected until the program checks the shape. With any, the same access is allowed even if it fails at runtime.
Note
Interview approach: define the concept, explain why it matters, then mention one trade-off or limitation.
Unknown requires proof
function read(value: unknown) {
if (typeof value === "string") return value.toUpperCase();
return "not a string";
}💡 The runtime check proves the value is a string before the string method is used.
Key Takeaways
- Explain the concept in your own words.
- Know the practical trade-off and its limits.
- Use a small example to demonstrate the idea.
Knowledge Check
Which type forces callers to narrow before accessing arbitrary properties?