any vs unknown — how do you handle unknown data?
Answer out loud or in your head first, then compare.
Answer
any lets you skip type checking for a value. unknown requires checking the type before you use it.
TypeScript
function label(value: unknown): string {
if (typeof value === 'string') return value.trim();
if (typeof value === 'number') return String(value);
return 'Unknown value';
}In practice: I treat data from outside the app as unverified and validate its structure at runtime, with a type guard or a validation library.
Pitfall: data as User is a promise to the compiler, not a check of the data. Bad data can still reach the app.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- B04 · Why do we check API data at runtime? What is unknown for? — JavaScript, TypeScript and Node.js
Practise in code
- Warm-up: checking input — runs tests in your browser