Type Guard
ELI5 — The Vibe Check
A type guard is like a bouncer at a club checking IDs. Before your code enters the VIP section, the guard checks 'are you a string or a number?' and TypeScript remembers the answer so you don't get type errors inside.
Real Talk
A TypeScript expression that performs a runtime check to narrow the type of a variable within a conditional block. Type guards use typeof, instanceof, 'in' operator, or custom type predicate functions (paramName is Type) to help the compiler understand the exact type at a specific point in code.
Show Me The Code
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function process(input: string | number) {
if (isString(input)) {
// TypeScript knows input is string here
console.log(input.toUpperCase());
} else {
// TypeScript knows input is number here
console.log(input.toFixed(2));
}
}
When You'll Hear This
"Write a type guard for your API responses so TypeScript knows the shape after validation." / "Custom type guards with 'is' predicates are cleaner than casting everywhere."
Related Terms
Discriminated Union
A discriminated union is like a box that could contain a cat, a dog, or a fish — but it has a label on the outside telling you which one.
Type Inference
Type inference is the compiler being smart enough to figure out what type something is without you having to spell it out.
Type Narrowing
Type narrowing is TypeScript being a detective.
TypeScript
TypeScript is JavaScript with a strict parent watching over it.