A question mark makes subtitle optional. So a book may have one, or not. Inside full title, we check for a subtitle, before using it. Run it. Dune has no subtitle. Sapiens shows its subtitle too.
main.tstypescript
interface Book { title: string; subtitle?: string;}function fullTitle(book: Book): string { if (book.subtitle) { return `${book.title}: ${book.subtitle}`; } return book.title;}console.log(fullTitle({ title: "Dune" }));console.log(fullTitle({ title: "Sapiens", subtitle: "A Brief History of Humankind" }));
A vertical bar means, or. Number, or string, accepts either one. A union of exact strings, like paperback, or hardback, or ebook, allows only those words. And type gives the union a name, so we can reuse it.
Format can only be one of three words. Show accepts a number, or a string. Type of tells us which one we have, and TypeScript then allows the right methods. Run it. Ebooks ship free. And each id is shown its own way.
main.tstypescript
type Format = "paperback" | "hardback" | "ebook";function shipping(format: Format): number { return format === "ebook" ? 0 : 2.99;}function show(id: number | string) { if (typeof id === "number") { console.log(`Book number ${id.toFixed(0)}`); } else { console.log(`Book code ${id.toUpperCase()}`); }}console.log(shipping("ebook"), shipping("hardback"));show(42);show("isbn-0441013597");
Audiobook isn't one of the formats. Run it. TypeScript rejects it, because audiobook is not a Format.
main.tstypescript
type Format = "paperback" | "hardback" | "ebook";function shipping(format: Format): number { return format === "ebook" ? 0 : 2.99;}console.log(shipping("audiobook"));
Output
main.ts(7,22): error TS2345: Argument of type '"audiobook"' is not assignable to
parameter of type 'Format'.