TypeScript Narrowing & Type Guards

Help TypeScript understand which type you have.

✍️ 3 exercises + code challenge in this lesson

Narrowing means checking a value so TypeScript knows its exact type in a branch:

  • typeof x === "string"
  • x instanceof Date
  • "swim" in animal
  • Discriminated unions: a shared kind property tells the variants apart.

Key Takeaways: TypeScript Narrowing & Type Guards

Mastering TypeScript Narrowing & Type Guards helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

TypeScript Narrowing & Type Guards Code Example

TypeScript
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":
      return Math.round(Math.PI * s.radius ** 2);
    case "square":
      return s.side ** 2;
  }
}

console.log(area({ kind: "circle", radius: 2 }), area({ kind: "square", side: 3 }));
Output
13 9
Free sign-in required · Google login available

TypeScript Narrowing & Type Guards Practice Exercises

Check what you learned in “TypeScript Narrowing & Type Guards”.

/ 3 solved
Fill in the blank

Check whether value is a Date.

if (value  Date) { }
✓ Correct! Not quite. Try again.
Multiple choice

What is a discriminated union?

✓ Correct! Not quite. Try again.
Code challenge

Write len(x: string | string[]) that returns x.length for both. Log len("abc") and len(["a", "b"]) separated by a space.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services