typestar

Narrowing and type guards in TypeScript

Teaching the compiler what a value actually is.

type Input = string | number | string[] | null;

function length(input: Input): number {
  if (input === null) return 0;
  if (typeof input === "string") return input.length;
  if (typeof input === "number") return String(input).length;
  if (Array.isArray(input)) return input.length;
  return 0;
}

function isUser(value: unknown): value is { name: string } {
  return typeof value === "object" && value !== null && "name" in value;
}

How it works

  1. typeof and Array.isArray narrow a union.
  2. Each check removes possibilities from the type.
  3. value is X declares a custom type guard.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
424
Tokens
108
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 1 of 4 in Narrowing, step 7 of 23 in Types & annotations.

← Previous Next →