typescript · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which toys pass the checks? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Toy { name: string; price: number }
function readToy(value: unknown): Toy | null {
if (typeof value !== "object" || value === null) return null;
if (!("name" in value) || typeof value.name !== "string") return null;
if (!("price" in value) || typeof value.price !== "number") return null;
return { name: value.name, price: value.price };
}
const items: unknown[] = JSON.parse('[{"name": "kite", "price": 8}, {"name": "yo-yo", "price": "2"}, null]');
const toys = items.map((item) => readToy(item)).filter((toy) => toy !== null);
console.log(toys.length, toys);
your turn
Your turn. Validate a high score.
Fill in the two types so a score needs a string player and a number of points. Then try breaking the JSON text and watch null appear.
fix it
null slipped past the first check. Fix it!
- Read the error:
TS18047: 'value' is possibly 'null'.Sneaky:typeof nullis"object"too. - The first check needs a second part that refuses
null. - Add
|| value === nullaftertypeof value !== "object"on line 3, then press run.
nailed it
your data has to earn its label now. :D
- Validate unknown data before giving it a type.
- Check it is an object, not
null, then check each property. - Return
nullwhen the data does not fit.
new words in your collection
- validate
This lesson isn’t saved. A free account remembers every lesson you finish.