Dev Highlights

Доки по разработке

This project is maintained by teniryte

Type predicates (пользовательские предикаты)

Принципы

Пример

interface Person {
  firstName: string;
  surname: string;
}

interface Organisation {
  name: string;
}

type Contact = Person | Organisation;

function isPerson(contact: Contact): contact is Person {
  return (contact as Person).firstName !== undefined;
}

function isOrganization(contact: Contact): contact is Organisation {
  return (contact as Organisation).name !== undefined;
}

function sayHello(contact: Contact) {
  if (isPerson(contact)) {
    console.log(contact.firstName);
  } else if (isOrganization(contact)) {
    console.log(contact.name);
  }
}

Практика