Narrowing

typeof and in.

typeof and in narrow a union so you can use the field.

Goal

Log a number or a city string.

function show(value: string | number): void {
  if (typeof value === "number") {
    console.log("units", value);
  } else {
    console.log("city", value.toUpperCase());
  }
}
show(12);
show("Nairobi");
type Row = { city: string } | { units: number };
function label(row: Row): string {
  if ("city" in row) return row.city;
  return String(row.units);
}
console.log(label({ city: "Mombasa" }));
console.log(label({ units: 8 }));
function ready(n: number | null): number {
  if (n === null) return 0;
  return n;
}
console.log(ready(null));
console.log(ready(5));
const city: unknown = "Kisumu";
if (typeof city === "string") {
  console.log(city.length);
}