CricketScript Lesson 11 of 11 · All-rounders  |  Course

All-rounders.

A type guard tells TypeScript which kind of player you've got.

A batter holds a bat. A bowler holds a ball. An all-rounder holds both. They sit in three boxes — and the captain has to ask each one the right question. Hand the bowler the bat in the powerplay, or ask the keeper to bowl the 19th over, and the day comes apart.

A type guard is the captain's check. A function that returns player is AllRounder doesn't just say true or false — it tells TypeScript what you've proven. Inside the if-block, the player is narrowed to an all-rounder, and the all-rounder's methods become available.

Tap each player. Watch the guard narrow them — and only the right methods light up.

Tap a player. The guard checks their role.
value
guard
narrowed
can bat?
can bowl?

The guard tells the compiler what you've proven.

player is AllRounder is the return type of a type predicate. When it's true, the compiler narrows the player in the branch — and only the right methods are reachable.

interface Batter     { name: string; bat(): void; }
interface Bowler     { name: string; bowl(): void; }
interface AllRounder extends Batter, Bowler {}

type Player = Batter | Bowler | AllRounder;

function isAllRounder(p: Player): p is AllRounder {
  return 'bat' in p && 'bowl' in p;
}

function deploy(p: Player) {
  if (isAllRounder(p)) {
    p.bat();   // ok — narrowed to AllRounder
    p.bowl();  // ok — narrowed to AllRounder
  } else if ('bat' in p) {
    p.bat();   // narrowed to Batter
  } else {
    p.bowl();  // narrowed to Bowler
  }
}

You've finished the course.

Type guards close the loop. A union of types says "could be any of these." A guard says "here, in this branch, it's exactly this one." Inside the narrowed block, all the right methods light up — and the wrong ones simply don't.

Use in for property checks, typeof for primitives, instanceof for classes, and custom predicates (x is T) when none of those fit. Narrow first. Then act.

Eleven lessons. One playing XI of TypeScript.

Primitives, arrays, tuples, interfaces, unions, functions, optionals, aliases, enums, generics, narrowing. You've taken the field.

The press box has filed. The honours board is set. Claim your honours →

One bonus innings: the 12th man → — all eleven concepts in one real match.

When you're done, bowl the next over → — five places to keep playing TypeScript.

Reading a paid lesson? The rest is right here.

This is one of 9 paid lessons. Lessons 1 and 9 are free previews if you want to sample first — otherwise the full course unlocks in one click.

$15worldwide · ₹625India (50% off)
Unlock all 11 lessons + bonus →
30-day money-back guarantee · Try Lessons 1 and 9 free first if you'd rather
Made by one person, not a company. Questions: [email protected]