Custom TypeScript type guards

Type guards let you provide TypeScript with more information about a variable’s type. Type guards are especially useful when working with a variable which may be undefined.

function lower(s: string | undefined): string {
  return s.toLowerCase()
}

The above code won’t compile1, as TypeScript doesn’t know whether s is a string or undefined. We can fix this problem using a type guard.

function lower(s: string | undefined): string {
  return typeof s === 'string' ? s.toLowerCase() : ''
}

Another option is to create a type guard function.

function isString(s: unknown): s is string {
  return typeof s === 'string'
}

function lower(s: string | undefined): string {
  return isString(s) ? s.toLowerCase() : ''
}

The magic ingredient in the above example is the s is string return value. This type predicate turns a function which returns a boolean into a type guard.

Footnotes

  1. If you’re using “strict” mode, which you are.

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.