22 May 2022

TIL you can have type predicates in TypeScript

TIL in TypeScript you can have type predicates, where the return value of your function indicate the type of an argument.

Instead of:

function isUserRole(role: string): boolean { }

…you can do:

function isUserRole(role: string): role is UserRole { }

That can be used to inform the type system of the value’s type, letting you do this:

const validatedRole =
  isUserRole(roleInput) ?
    roleInput :
    undefined;

…and use validatedRole as an optional UserRole rather than just a string.

Categories

Programming TypeScript Today I Learned (TIL)