Type Guard Custom
Predict Output Medium
Question
What does this code print?
Code
function isNum(x: any): x is number { return typeof x === "number"; }
function fn(v: any) {
if (isNum(v)) return v.toFixed(2);
return "N/A";
}
console.log(fn(3.14159));
Hint
Custom type guard narrows v to number.
Explanation
isNum is a custom type guard (x is number). When it returns true, TypeScript narrows v to number. v.toFixed(2) rounds to 2 decimal places: 3.14159 → "3.14".
Related Resources
Related Lessons
- Type Guards
Learn type guards.
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.