Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Narrow types inside switch (true)

Use switch (true) to narrow values with different boolean checks in TypeScript 5.3 and later.

To format a value that might be a string, a number, a date or null, you need different checks for different types. switch (true) gives those checks a shared structure.

function label(value: string | number | Date | null) {
  if (value === null) {
    return 'empty'
  } else if (typeof value === 'number') {
    return value.toFixed(2)
  } else if (value instanceof Date) {
    return value.toISOString()
  } else {
    return value.trim()
  }
}

Each branch sees the narrowed type. The same checks fit into a switch if you compare each case with true.

Switch on true

switch (true) starts at the first case whose expression is true. Each case can hold a boolean check. Until TypeScript 5.3 the compiler treated those expressions as plain booleans and value stayed the full union inside every case. From 5.3 it narrows per case, the same as the if/else chain.

function label(value: string | number | Date | null) {
  switch (true) {
    case value === null:
      return 'empty'
    case typeof value === 'number':
      return value.toFixed(2)
    case value instanceof Date:
      return value.toISOString()
    default:
      return value.trim()
  }
}

With --strict this compiles clean on 5.3, and label(3.14159) prints 3.14. The default branch narrows too; value is string there because every other member of the union has been handled above it.

What 5.2 said

TypeScript 5.2 keeps the original union in the cases. For example, it reports that value might be null and that toFixed is unavailable on string | number | Date.

Fall-through still applies

When execution can fall through a case, TypeScript accounts for the types that can reach the next case from either path. The release notes show case typeof x === "string" falling into case Array.isArray(x), where x is string | any[], since control can arrive from either check. Return from each case to keep the checks independent.

I use switch (true) when the checks are mixed, as above. When every branch tests the same property, switch (value.kind) reads better, and a never check in its default branch makes the compiler name a missing case.