Dev Highlights

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

This project is maintained by teniryte

Утверждения сужения (asserts)

Принципы

Пример

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

interface Organisation {
  name: string;
}

type Contact = Person | Organisation;

function assertIsPerson(contact: Contact): asserts contact is Person {
  if ((contact as Person).firstName === undefined) {
    throw new Error('Not a person');
  }
}

function sayHello(contact: Contact) {
  assertIsPerson(contact);
  console.log('Hello ' + contact.firstName);
}

Практика