TypeScript Developer interview question · Most asked
Explain `any`, `unknown` and `never`.
Summary
any disables type checking for a value; unknown is the type-safe top type: anything can be assigned to it, but you must narrow it before use; never is the bottom type for values that never occur (functions that throw, exhaustive checks).
Longer Answer
Prefer unknown for untrusted input (JSON, catch variables with useUnknownInCatchVariables) and narrow with typeof, instanceof or schema validation. any spreads silently through code and should be rare (lint with no-explicit-any). never is useful in exhaustive switch statements: assigning the remaining value to never makes the compiler error when a new union member is added.
Code Example
function parse(json: string): unknown {
return JSON.parse(json);
}
const data = parse('{"name":"Ana"}');
// data.name; // Error: 'data' is of type 'unknown'
if (typeof data === "object" && data !== null && "name" in data) {
console.log((data as { name: string }).name);
}
function assertNever(x: never): never {
throw new Error(`Unexpected: ${JSON.stringify(x)}`);
}
Key Points
any: opt out of checking (contagious)unknown: must narrow before usenever: impossible values, exhaustiveness- Prefer
unknownfor external data
Comparison / Tradeoffs
| Type | Assign anything to it? | Use without checks? |
|---|---|---|
| any | Yes | Yes (unsafe) |
| unknown | Yes | No, narrow first |
| never | No | N/A |
More most-asked TypeScript Developer questions
- What is TypeScript and what problems does it solve?
- What is structural typing in TypeScript?
- What are the differences between `interface` and `type` aliases?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is type narrowing and what techniques does TypeScript support?
- What are mapped types? Show how `Partial` or `Readonly` could be implemented.