Type Guard Purpose
Question
What is a type guard?
Hint
Type guards enable safe access to type-specific properties.
Explanation
A type guard is a runtime check that narrows a type within a conditional block. Built-in guards: typeof (for primitives), instanceof (for classes), in (for property existence). Custom type guards use a predicate: function isString(x: any): x is string { return typeof x === "string"; }. Inside the if block, TypeScript narrows the type, allowing access to type-specific properties. Type guards are essential for working with union types safely.
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.