Explain the difference between any and unknown, and demonstrate type-safe narrowing
This tests your grasp of TypeScript top types: any disables checking while unknown forces narrowing. A strong answer defines both, accepts unknown, and uses typeof or a type guard before operating. Red flag: saying they are equivalent or relying on as casts.
WHAT THIS TESTS: This question evaluates whether you understand the distinction between TypeScript's two top types and why one is safe while the other is a compiler escape hatch. any tells the compiler to trust you and disables static checking, so you can access any property or call it as a function without complaint. unknown also represents any possible value, but the compiler refuses to let you use it until you prove what it is through narrowing. The interviewer wants to see that you choose unknown for external inputs and that you know how to narrow it without resorting to type assertions.
A GOOD ANSWER COVERS: First, a crisp definition of the difference: any is unsound and contagious, while unknown is type-safe. Second, a small function signature such as function processValue(value: unknown): string. Third, at least one narrowing strategy inside the body, for example checking typeof value === "string" and then calling value.trim(), or using instanceof for classes, or a user-defined type guard like isUser. Fourth, a brief rationale for why unknown is preferable for API responses, JSON.parse results, or generic catch clauses.
COMMON WRONG ANSWERS: Treating unknown as a stricter synonym for any rather than a completely different contract. Writing a function that accepts unknown but immediately casts it using a type assertion such as SomeType instead of narrowing. Saying that unknown cannot be assigned to variables, when in fact any value can be assigned to an unknown variable; the restriction is on reading or operating on it. Using any because it is easier and defending it as best practice for production code.
LIKELY FOLLOW-UPS: The interviewer might ask when any is ever justified, such as during incremental JavaScript migration or inside generated code. They might ask how unknown relates to never, or how to narrow an unknown into a discriminated union or an object with a specific interface. Another follow-up is how to handle an unknown error in a catch block under newer TypeScript settings.
ONE CONCRETE EXAMPLE: Write a function named formatInput that takes input: unknown and returns a string. Inside, first check if typeof input === "string"; if so, return input.toLowerCase(). Next, check if typeof input === "number"; if so, return input.toFixed(2). If neither type matches, throw new Error("Unsupported input"). This demonstrates progressive narrowing, keeps the operation type-safe, and never uses any or a type assertion.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.