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 →

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

Beta preview — free while in beta

All 11 lessons are open. No signup, no payment, no gate. I'm iterating on the lessons for a few weeks before the full release — everything you see is free during that window.

Spotted a bug or have a suggestion? Email [email protected] — beta feedback is the whole point.