In this lesson, you pinned Harbor Line’s port names down so that a misspelled port can’t reach the departures board.
Key Points
- A literal type is one exact value. A
constholding"Gull Island"has the type"Gull Island", while aletwith the same value has the typestring, because aletcan change later. - A union of literal types is a fixed set of options.
type Port = "Port Wren" | "Gull Island" | "Heron Key" | "Tern Rock";accepts those four names and nothing else, so the check rejects"Heron Cay"withArgument of type '"Heron Cay"' is not assignable to parameter of type 'Port'.The check only reports the typo, though. Node strips the types without checking them, sonode ports.tsstill runs and printsKittiwake to Heron Cay. - Object properties widen.
const crossing = { id: "HL-0815", to: "Heron Key" };givestothe typestring, because you can still change a property of aconstobject. ACrossingtype,type Crossing = { id: string; to: Port };, keepstoaPort. You can still change it, but only to anotherPort. - Array items widen too, and
as constpins them. Without it, the ports list is astring[]. With it, the list isreadonly ["Port Wren", "Gull Island", "Heron Key", "Tern Rock"], so it can’t be changed and each item keeps its literal type. A misspelled name in the list would still fail the check. It works the same way after an object literal: each property keeps its literal type and becomes readonly, so{ to: "Heron Key" } as consthas the readonly propertyto: "Heron Key". as constdoesn’t freeze anything. It changes only what the checker knows. Node strips it with the other types, soObject.isFrozen(ports)printsfalse.
Final Code
Here’s ports.ts as the lesson leaves it. The Port union names the four ports, the Crossing type keeps a crossing’s to property a Port, and as const keeps each name in the list at its literal type, so every call to boardLine() gets a real port:
ports.ts
type Port = "Port Wren" | "Gull Island" | "Heron Key" | "Tern Rock";
type Crossing = { id: string; to: Port };
function boardLine(to: Port) {
return `Kittiwake to ${to}`;
}
const crossing: Crossing = { id: "HL-0815", to: "Heron Key" };
console.log(boardLine(crossing.to));
const ports = ["Port Wren", "Gull Island", "Heron Key", "Tern Rock"] as const;
for (const port of ports) {
console.log(boardLine(port));
}
Run the check, then the file. The check is clean, and the board shows the crossing’s port followed by all four ports:
$ npm run check
> [email protected] check
> tsc --noEmit
$ node ports.ts
Kittiwake to Heron Key
Kittiwake to Port Wren
Kittiwake to Gull Island
Kittiwake to Heron Key
Kittiwake to Tern Rock