100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
TypeScript

Type Guards in TypeScript

Narrow union types safely within conditional blocks using `typeof`, `instanceof`, and custom user-defined type predicates with `is`.

Advanced TypesAdvanced13 min readJul 8, 2026
Analogies

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

typescript
// 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

typescript
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

text
splash
swimming
flap
flying
HELLO
3.14
null value

6. Key Takeaways

  • typeof, instanceof, and in are 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

Was this page helpful?

Topics covered

#TypeScript#TypeScriptProgrammingStudyNotes#Programming#TypeGuardsInTypeScript#Type#Guards#Syntax#Explanation#StudyNotes#SkillVeris