On this page
  1. is
  2. Syntax & Overview
  3. Notes & Pitfalls
  4. Example

is

Prev: `readonly` | Up: builtins | Next: `asserts`
Rel: builtins, Structural Typing & Narrowing
Ref: TypeScript Docs — is
Tags: #public #web #typescript #builtins #tier/standard


Syntax & Overview

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

User-defined type guard return annotation that narrows a parameter's type in the calling scope when the function returns true.

Notes & Pitfalls

Example

interface Cat { meow(): void }
interface Dog { bark(): void }

function isCat(pet: Cat | Dog): pet is Cat {
  return "meow" in pet;
}

function speak(pet: Cat | Dog) {
  if (isCat(pet)) pet.meow();
  else pet.bark();
}

Linked from

Related notes