In Naming Shapes With type and interface, you gave Harbor Line’s foot tickets and car tickets names built on one shared base, and you’ve since named the boats and crew the same way. The ticket counter sells both kinds, though, and a day’s sales go into one list. Neither FootTicket nor CarTicket fits every item in it.
In this lesson, you’ll write union types for values that can be one of several types, from a departure time to a ticket of either kind. You’ll be able to predict which properties the checker lets you read on a union and read the error line that names the member missing a property. Start with a union you’ve already met, for a departure time.
Recap a Union of Two Primitives
A value that arrives in two forms needs a type that allows both. Harbor Line’s new timetable writes a departure time as text, such as "8:15", while the old one counted minutes after midnight, such as 495. You’ve typed this kind of value before as string | number, where the vertical bar means or.
You’ve also seen the checker reject the number-only method .toFixed() on it, because a string has no such method. A string-only method such as .padStart() hits the same rule from the other side.
The typeof check you’ve used on unknown values is what makes that method available. Here’s a short reminder, with the union named the same way you named the ticket shapes:
times.ts
1type DepartureTime = string | number;
2
3function boardTime(time: DepartureTime) {
4 if (typeof time === "string") {
5 return time.padStart(5, "0");
6 } else {
7 return `${time} minutes after midnight`;
8 }
9}
Inside the if on line 4, the checker knows that time is a string, so .padStart() on line 5 is allowed. The else branch shows a minute count as is, with a template literal that needs no string-only method.
Giving a value a narrower type inside a check’s branch, here string instead of DepartureTime, is called narrowing, and that’s all you need to know about narrowing for now. It gets a lesson of its own later in this course.
Join the Ticket Shapes With |
The same bar joins object shapes, and that’s what the sales list needs. Each sale is a foot ticket or a car ticket, so the type of a sale is FootTicket | CarTicket.
Open tickets.ts from the last lesson. Add line 13, delete receiptLine() and the two console.log() calls, and then add lines 29 to 37 at the end:
tickets.ts
1type TicketBase = {
2 id: string;
3 crossingId: string;
4 priceCents: number;
5};
6
7type FootTicket = TicketBase & { passenger: string };
8type CarTicket = TicketBase & {
9 lengthFeet: number;
10 plate: string;
11};
12
13type Ticket = FootTicket | CarTicket;
14
15const miraTicket: FootTicket = {
16 id: "T-1041",
17 crossingId: "HL-0815",
18 priceCents: 850,
19 passenger: "Mira Okafor",
20};
21const tomasTicket: CarTicket = {
22 id: "T-1042",
23 crossingId: "HL-0815",
24 priceCents: 4200,
25 lengthFeet: 15,
26 plate: "7KQM214",
27};
28
29const sales: Ticket[] = [miraTicket, tomasTicket];
30
31function deckLine(ticket: Ticket) {
32 return `${ticket.id}: ${ticket.plate}`;
33}
34
35for (const ticket of sales) {
36 console.log(deckLine(ticket));
37}
Line 13 names the union Ticket. Line 29 types the sales list as Ticket[], an array in which each item has one of the two shapes. Mira’s ticket fits because it matches FootTicket, and Tomás’s fits because it matches CarTicket. The name Ticket also spares you the parentheses that (FootTicket | CarTicket)[] would need.
Why not type the list as TicketBase[], since both tickets have every property of the base? That type would accept both tickets, but it keeps only the three shared properties and forgets that each sale is one of two kinds. The union keeps both shapes, and later lessons use that to tell a foot ticket from a car ticket.
The car deck crew wants a list of the plates on each crossing, so an AI assistant suggested deckLine() on lines 31 to 33, with a loop that prints a line for every sale. It reads two properties of each ticket, its id and its plate. Before you run the check, predict which of those two reads the checker accepts on a Ticket, and why.
The checker rejects one of the two reads:
$ npm run check
> [email protected] check
> tsc --noEmit
tickets.ts:32:34 - error TS2339: Property 'plate' does not exist on type 'Ticket'.
Property 'plate' does not exist on type 'FootTicket'.
32 return `${ticket.id}: ${ticket.plate}`;
~~~~~
Found 1 error in tickets.ts:32
Reading ticket.id is fine, and reading ticket.plate isn’t. On a union, the checker allows only what every member has. Both members get id from TicketBase, but only CarTicket has a plate, and a Ticket might be a foot ticket.
The error tells you this in two lines. The first line says what’s wrong with the union as a whole: Ticket has no plate. The indented line names the member that causes it, FootTicket. So the trouble comes from the foot tickets among the sales.
Read Which Member the Error Names
Is the rejected read a real problem, or is the checker being fussy? Run the file to see what the crew’s list would show:
$ node tickets.ts
T-1041: undefined
T-1042: 7KQM214
Node.js ran the code without a complaint because it strips the types without checking them. Mira is a foot passenger with no car, yet the list gives her ticket a line with an undefined plate. The suggestion puts every sale on the car deck list, and the checker caught that bug in code that looked fine.
Fix the type so it says what the function needs. Only a car ticket has a plate, so change the parameter on line 31 to ticket: CarTicket. Run the check again, and the error moves to the loop. Its long lines are wrapped here for display:
$ npm run check
> [email protected] check
> tsc --noEmit
tickets.ts:36:24 - error TS2345: Argument of type 'Ticket' is not
assignable to parameter of type 'CarTicket'.
Type 'FootTicket' is not assignable to type 'CarTicket'.
Type 'FootTicket' is missing the following properties from type
'{ lengthFeet: number; plate: string; }': lengthFeet, plate
36 console.log(deckLine(ticket));
~~~~~~
Found 1 error in tickets.ts:36
Read it from the top, as before. Line 36 passes a Ticket where a CarTicket is expected. The next line names the member that doesn’t fit, FootTicket, and the last line lists the properties it lacks: lengthFeet and plate.
The checker is right again, because any sale might be Mira’s foot ticket. Picking the car tickets out of sales takes a check on each item, and typeof can’t do it here, since it gives "object" for both kinds of ticket. Later lessons in this course show you how to tell object shapes apart.
For now, replace the loop on lines 35 to 37 with console.log(deckLine(tomasTicket));. The check passes, and node tickets.ts prints T-1042: 7KQM214, a line for the one car on the crossing.
Take care not to mix up the | with the & from the last lesson. FootTicket & CarTicket would describe a ticket that’s both at once, with a passenger, a length, and a plate. FootTicket | CarTicket describes a ticket that’s either one. An intersection lets you read more properties on fewer values, while a union lets in more values and allows only the properties every member shares.
Want to practice predicting what a union allows?
Check Your Understanding
Try these before you open the answers. They use the types from this lesson.
- Harbor Line numbers its gates on the mainland, such as
2, and letters them on the islands, such as"B". Write a named type for a gate, and use it for the parameter offunction gateSign(gate) { return `Gate ${gate}`; }. - In a function that takes
ticket: Ticket, the checker allowsticket.crossingIdbut rejectsticket.passenger. Explain why, and say which member the error’s second line names. - A teammate suggests
type Ticket = FootTicket & CarTicket;so thatticket.plateis allowed. Explain why that breaks thesaleslist.
- Write
type Gate = number | string;, then annotate the parameter asgate: Gate. The template literal works for both members, so the function needs notypeofcheck. - Both members get
crossingIdfromTicketBase, so everyTickethas one. OnlyFootTickethas apassenger, so aTicketthat’s a car ticket wouldn’t have one, and the error’s second line namesCarTicket. - Every sale would then need a passenger, a length, and a plate. Mira’s ticket has no length or plate, and Tomás’s has no passenger, so the check rejects both, starting with
Type 'FootTicket' is not assignable to type 'Ticket'.No real sale fits the intersection. A union accepts a ticket that fits at least one of the shapes, while an intersection accepts only a ticket that fits both.
You can now write a union for a value that really varies and predict that the checker lets you read only what every member has. One gap remains, though. The line’s ports and timetable are still typed as plain strings, so a misspelled port name passes the check.
Next up is Pinning Options With Literal Types, a video where you’ll tell the checker that a port can only be one of Harbor Line’s four ports.