×

typescript · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A teaches the checker your own test.

Data from outside, such as JSON, should arrive as unknown. You can check it with typeof and in, but that narrowing only lasts inside one if. Move the checks into a function and the narrowing is lost, unless the function says what its answer proves.

A return type like value is Pet is a . The function returns a boolean, and when the answer is true the checker treats the value as a Pet. A function like that is a type guard: write it once and reuse it everywhere.

interface Pet {
  name: string;
  age: number;
}
function isPet(value: unknown): value is Pet {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  return "name" in value && typeof value.name === "string" && "age" in value && typeof value.age === "number";
}
const data: unknown = JSON.parse('{"name": "Rex", "age": 4}');
if (isPet(data)) {
  console.log(`${data.name} is ${data.age}`);
}

The checker trusts a type predicate completely, so make sure the checks inside are honest.