×

typescript · level 2 · unit 7 · 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

data before you trust it, one property at a time.

A reply from a server could be anything. To validate it is to check it has the shape you need before you use it. Write a function that takes unknown and gives back a typed object, or null if the data does not fit.

First check it is an object: typeof value === "object" && value !== null, because typeof null is also "object". Then "name" in value checks the property is there. Even then value.name is unknown, so check its type too.

Only when every check passes do you build the typed object. Now the label is a proof, not a promise.

interface Pet { name: string; age: number }
function readPet(value: unknown): Pet | null {
  if (typeof value !== "object" || value === null) return null;
  if (!("name" in value) || typeof value.name !== "string") return null;
  if (!("age" in value) || typeof value.age !== "number") return null;
  return { name: value.name, age: value.age };
}
console.log(readPet(JSON.parse('{"name": "Rex", "age": 3}')));
console.log(readPet(JSON.parse('{"name": "Tom"}')));
console.log(readPet(JSON.parse('"Kit"')));

Each check guards one door. Miss one and bad data can sneak through.