type Parcel = | { status: "packed"; id: string; kg: number } | { status: "shipped"; id: string; kg: number; tracking: string } | { status: "delivered"; id: string; kg: number; tracking: string; deliveredOn: string } | { status: "returned"; id: string; kg: number; reason: string }; const parcels: Parcel[] = [ { id: "A1", status: "packed", kg: 2.5 }, { id: "B2", status: "shipped", kg: 1.2, tracking: "1Z999" }, { id: "C3", status: "delivered", kg: 4, tracking: "1Z123", deliveredOn: "Nov 20" }, { id: "D4", status: "shipped", kg: 0.8, tracking: "1Z456" }, { id: "E5", status: "returned", kg: 3.1, reason: "wrong size" }, ]; function unreachable(p: never): never { throw new Error(`Unhandled parcel: ${JSON.stringify(p)}`); } function describe(p: Parcel): string { switch (p.status) { case "packed": return `${p.id}: packed, waiting for pickup`; case "shipped": return `${p.id}: on its way, tracking ${p.tracking}`; case "delivered": return `${p.id}: delivered ${p.deliveredOn}`; case "returned": return `${p.id}: sent back (${p.reason})`; default: return unreachable(p); } } let total = 0; for (const p of parcels) { console.log(describe(p)); total += p.kg; } console.log(`Total weight: ${total} kg`); // Try this next… // // 1. Write a function `trackingOf(p: Parcel)` that returns a parcel's tracking // number, without writing its return type. What type did the checker work // out, and why can't it be plain `string`? Run `tsc --declaration // parcels.ts` and read the answer in parcels.d.ts. // // 2. Add a parcel to the list with `as Parcel` after it, and leave out its // tracking number. The checker goes quiet. Run the program and find the // `undefined` that comes back. `as` is you overruling the checker. // // 3. Change `p: Parcel` in `describe` to `p: any`. How many of the bugs from // the article could come back without a single error? Try reintroducing // the "deliverd" typo and see. // // 4. Replace the list with `JSON.parse(...)` of the same data written as a // string, with "kg": "4" for one parcel. The program compiles and the total // is wrong again. The types were never checked against the data. What would // you have to write to check it while the program runs? // // 5. Build with `tsc --noEmitOnError parcels.ts` and break something. Now the // checker can stop the JavaScript from being written. Would you want that // on all the time? // // 6. Print only the parcels still on their way with // `parcels.filter((p) => p.status === "shipped")`, then read each one's // `tracking`. Does the checker follow the narrowing through `filter`?