Narrowing Objects, Dates and Lists

In the last video, the checker followed truthiness, !== undefined, and early-return checks, which rule out a missing value or tell primitives apart. Harbor Line’s notices hold other kinds of values: a reading may carry a wind speed, a time can be a Date or an old "08:15" string, and a notice’s text can be one line or a list.

You’ll pick the check that narrows each union, predict each branch’s type, and confirm it with a hover. Start with the reading, whose members differ by one property.

Check for a Property With in

Both members of a reading are objects, so typeof can’t tell them apart. JavaScript’s in operator asks whether an object has a property, and the checker narrows on it. Create readings.ts:

Language: TypeScript Filename: readings.ts
 1type CalmReading = { station: string };
 2type WindReading = { station: string; windKnots: number };
 3type Reading = CalmReading | WindReading;
 4
 5function readingLine(reading: Reading) {
 6  if ("windKnots" in reading) {
 7    return `${reading.station}: wind ${reading.windKnots} knots`;
 8  }
 9  return `${reading.station}: no wind reading`;
10}
11
12console.log(readingLine({ station: "Gull Island" }));
13console.log(readingLine({ station: "Port Wren", windKnots: 18 }));

On line 7, the hover on reading shows (parameter) reading: WindReading, the only member with windKnots. Run the file:

Language: Shell
$ node readings.ts
Gull Island: no wind reading
Port Wren: wind 18 knots

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.