1. Introduction
A type guard is any expression that, when used in a conditional, lets TypeScript narrow a broader (often union) type down to a more specific type within a particular code branch. TypeScript ships several built-in narrowing mechanisms — typeof, instanceof, in, and equality checks against literal values — and also lets you define your own guards via custom functions with a type predicate return type (param is Type). Type guards are essential for working safely with union types without resorting to type assertions, which bypass the compiler's checks entirely.
Cricket analogy: Checking whether a bowler "is left-arm" via the team sheet before choosing a batting order lets the captain narrow decisions safely, unlike blindly asserting a bowling change without checking the actual data.
2. Syntax
// typeof guard
function printValue(v: string | number) {
if (typeof v === "string") {
v.toUpperCase(); // v: string here
}
}
// instanceof guard
class ApiError extends Error {}
function handle(e: Error | ApiError) {
if (e instanceof ApiError) {
// e: ApiError here
}
}
// user-defined type predicate
interface Fish { swim(): void; }
interface Bird { fly(): void; }
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
// `in` operator guard
function move(pet: Fish | Bird) {
if ("swim" in pet) {
pet.swim(); // narrowed to Fish
}
}3. Explanation
For primitive unions, typeof v === "string" (and similar checks for "number", "boolean", "undefined", etc.) is the standard narrowing tool, and TypeScript's control-flow analysis automatically narrows v's static type inside the corresponding branch. For class instances, instanceof narrows a union of class types by checking the prototype chain at runtime, letting you branch between Error and a subclass like ApiError safely.
Cricket analogy: typeof score === "number" narrows a union of raw score strings and computed totals so it's safe to do arithmetic on the actual run tally, like checking a scoreboard digit before adding overs.
When built-in operators are not expressive enough — for example distinguishing two structurally different interfaces that share no common literal discriminant — you write a custom type guard: a function whose return type is a type predicate paramName is SomeType. TypeScript trusts this predicate's boolean logic completely and narrows the argument's type in any branch where the function returns true. Type predicates are just a fiction the compiler trusts based on the annotation, not something it verifies against the implementation, so it is the author's responsibility to make sure the check inside the function actually corresponds to the predicate.
Cricket analogy: A custom function isSpinner(bowler): bowler is Spinner lets you distinguish spin from pace bowlers when there's no shared field to check, but the selectors trust your judgment completely -- mislabel a medium-pacer and nobody double-checks.
The in operator ("prop" in obj) is also a built-in narrowing mechanism: it narrows a union to the member(s) of the union that declare prop, which is useful for object shapes that don't have a class hierarchy or literal discriminant.
Gotcha: because a custom type predicate (x is T) is never checked against the function body by the compiler, a poorly written guard (e.g. one that always returns true) will compile fine and silently produce unsound narrowing, leading to runtime errors that TypeScript's static analysis will not catch. Always keep the runtime check and the declared predicate in sync.
4. Example
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
function isFish(pet: Bird | Fish): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function move(pet: Bird | Fish): string {
if (isFish(pet)) {
pet.swim();
return "swimming";
} else {
pet.fly();
return "flying";
}
}
const fish: Fish = { swim: () => console.log("splash"), layEggs: () => {} };
const bird: Bird = { fly: () => console.log("flap"), layEggs: () => {} };
console.log(move(fish));
console.log(move(bird));
function processValue(value: string | number | null) {
if (typeof value === "string") {
return value.toUpperCase();
} else if (typeof value === "number") {
return value.toFixed(2);
}
return "null value";
}
console.log(processValue("hello"));
console.log(processValue(3.14159));
console.log(processValue(null));5. Output
splash
swimming
flap
flying
HELLO
3.14
null value6. Key Takeaways
typeof,instanceof, andinare TypeScript's built-in narrowing (type guard) operators.- Custom type guards use a type predicate return type:
function f(x: A): x is B. - The compiler trusts a custom predicate's declared narrowing without verifying it against the function body.
- Type guards narrow types only within the scope of the conditional branch where they were checked.
- Prefer type guards over type assertions (
as) because guards are checked by control-flow analysis, not just asserted.
Practice what you learned
1. What is the return type annotation used to define a custom type guard function?
2. Which built-in operator narrows a union based on the presence of a property name on the runtime object?
3. Gotcha: does TypeScript verify that a custom type predicate's declared narrowing matches the function's actual runtime logic?
4. Which operator narrows a union of class types by checking the prototype chain at runtime?
5. In `processValue`, why is `typeof value === "number"` needed as a second check after the string check, rather than an unconditional `else`?
Was this page helpful?
You May Also Like
Discriminated Unions in TypeScript
Use a shared literal 'tag' property across union members so TypeScript can narrow exactly which member you're handling in a switch or if.
keyof and typeof Operators in TypeScript
Use `keyof T` to get a union of a type's property names, and `typeof x` in a type position to extract the type of a value.
Union and Intersection Types in TypeScript
Combine types with `|` (union) and `&` (intersection) to model values that can be one of several shapes or must satisfy all of them.
Type Assertions in TypeScript
Tell the compiler to treat a value as a more specific type using `as`, without performing any runtime conversion.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics