Distrito Telefónica. Innovation & Talent Hub
Let’s start with 3x Typescript models:
Type definitions in Typescript.
Highlight the common properties from the tree types
type
instead of
interface
, we may cover this particular in another post. In summary: prefer
type
over
interface
if you are defining object properties. Remember, it’s called
Typescript
, not
InterfaceScript
ticketType
property is telling which type is fulfilling out of the 3 options. We're defining its type as an
Union Type.
type TicketType = 'event-ticket' | 'coupon' | 'pass';
type CommonTicket = {
ticketType: TicketType;
code: string;
description?: string;
}
type EventTicket = CommonTicket & {
ticketType: 'event-ticket';
event: {
eventId: string;
eventName: string;
eventDate: Date;
};
};
type Coupon = CommonTicket & {
ticketType: 'coupon';
discountAmount: number;
minPurchaseAmount?: number;
expirationDate?: Date;
};
type Pass = CommonTicket & {
ticketType: 'pass';
startDate: Date;
endDate: Date;
remainingUses?: number;
service: {
serviceId: string;
serviceName: string;
};
};
type Ticket = EventTicket | Coupon | Pass;
if
statements:
event-ticket
and
pass
, so input
Ticket
is a
Coupon
- VsCode infers the type
Coupon
correctly:
Screenshot of a function in which we are checking first for event-ticket; the IDE infers the correct typing.
But What if we extract an aux. function?
Screenshot with a typescript error (explained below)
Property 'event' does not exist on type 'Ticket'
.
ticket
when extracting the type check to a function.
Type Predicates to the rescue
-function isAnEvent(ticket: Ticket) {
+function isAnEvent(ticket: Ticket): ticket is EventTicket {
return ticket.ticketType === 'event-ticket';
}
isAnEvent()
isn't returning just a boolean, now it's defining the type guard we need.
isAnEvent()
[..] is called with some variable, TypeScript will narrow that variable to that specific type if the original type is compatible.
Overloading
function getTicket(type: TicketType, code: string): Promise<Ticket> {
// when type is 'event-ticket' -> EventTicket
// when type is 'coupon' -> Coupon
// when type is 'pass' -> Pass
}
We would like to tell Typescript,
getTicket()
; Typescript will infer the exact type like a charm:
Correct infer of types