April 2018
Beginner
536 pages
13h 21m
English
We can define custom type guards using by declaring a function with a special return type:
interface Supplier { orderItems(): void; getAddress(): void;}interface Customer { sellItems(): void; getAddress(): void;}function isSupplier(person: Supplier | Customer): person is Supplier { return (<Supplier> person).orderItems !== undefined;}function handleItems(person: Supplier | Customer) { if (isSupplier(person)) { person.orderItems(); // OK } else { person.sellItems(); // OK }}
The preceding code snippet declares two types (Supplier and Customer); it then declares a custom type guard function. The custom type guard returns a Boolean value. The function returns true when the provided value person has a property named orderItems ...