Union Narrowing
Predict Output Easy
Question
What does this code print?
Code
function fn(x: string | number) {
if (typeof x === "string") return x.length;
return x;
}
console.log(fn(42));
Hint
typeof narrows x to number in the else branch.
Explanation
When x is 42 (number), the typeof check fails, so the else branch runs. TypeScript narrows x to number in the else branch. The function returns 42.
Related Resources
Related Lessons
- Type Narrowing
Learn narrowing.
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.