0Pricing
TypeScript Academy · Lesson

in, instanceof, discriminated unions

Use in/property checks, instanceof for classes, and discriminated unions to branch safely.

Intro

Goal: Practice three powerful guards: in for property checks, instanceof for classes, and discriminated unions for clean branching.

in operator

in narrows by testing a property name at runtime. Great for object-literal unions.

type HasLength = { length: number };

function print(v: string | HasLength) {
  if ("length" in v) {
    // v is HasLength
    console.log("len:", v.length);
  } else {
    // v is string
    console.log(v.toUpperCase());
  }
}

print({ length: 3 });
print("ts");

All lessons in this course

  1. typeof, equality, truthiness narrowing
  2. in, instanceof, discriminated unions
  3. Exhaustiveness with never (intro)
← Back to TypeScript Academy