Find: Incorrect Type Narrowing
Find the Mistake Medium
Question
This code has a type error. Find the mistake:
Code
function format(value: string | number) {
if (value) {
return value.toUpperCase();
}
return String(value);
}
Hint
Truthiness checks don't narrow union types. What type guard should be used?
Explanation
The if (value) check is a truthiness check, not a type guard. It does not narrow value to string — an empty string or 0 would be falsy, but non-empty numbers would be truthy. TypeScript still sees value as string | number inside the if block. Fix: use if (typeof value === 'string') to properly narrow the type.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.