In the last exercise, you formatted Harbor Line’s notices by checking whether each value was a wind reading, a Date, or a list. That leaves a question from the day you named the tickets. Back then, receiptLine() accepted a CarTicket for its TicketBase parameter, because the checker compares shapes, not names.
In this lesson, you’ll find out how far that rule goes. You’ll be able to predict whether a ticket fits a type from its properties alone and explain why a type’s name doesn’t keep two kinds of ticket apart. Start with the habit TypeScript borrows from JavaScript.
Fit a Type by Its Properties
The counter now sells bike tickets, and the crew at the bike rack needs a tag for each bike. In plain JavaScript, the tag function is the kind you’ve written for years:
function rackTag(ticket) {
return `Rack tag ${ticket.id}: ${ticket.passenger}`;
}
It reads two properties, ticket.id and ticket.passenger, so it works with any object that has them, whatever made that object.
To type it, define the bike ticket type first. A bike ticket names its rider, the same way a foot ticket names its passenger, and it costs 1,200 cents instead of 850. Open tickets.ts from the earlier lessons and add the new type on line 12, right below CarTicket:
12type BikeTicket = TicketBase & { passenger: string };
Then add the typed tag function and Kofi Mensah’s bike ticket at the end of the file, after a blank line. These are lines 38 to 49:
38function rackTag(ticket: BikeTicket) {
39 return `Rack tag ${ticket.id}: ${ticket.passenger}`;
40}
41
42const kofiTicket: BikeTicket = {
43 id: "T-1043",
44 crossingId: "HL-0815",
45 priceCents: 1200,
46 passenger: "Kofi Mensah",
47};
48
49console.log(rackTag(kofiTicket));