Boss lesson · Unit 06
An inventory that saves itself
Load stock from text, check it, change it, save it, and survive bad input
What you practise
- Parse JSON, check it at run time until the compiler trusts it, update stock, serialise it again, and survive bad input
Try a question from this lesson
Pick one
A shop keeps its stock as JSON text between runs. What does this print after loading it?
const saved = '[{"name":"pen","qty":3}]';
const items = JSON.parse(saved);
console.log(items[0].qty + 1);Correct answer
4
Why
JSON.parse rebuilds real data from the text: an array holding one object, whose qty is the number 3. So + 1 adds. Note what the compiler knows about items, though: nothing. Its type is any.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Out is safe, in is not
The job: load stock from text, change it, save it again, and never crash on bad text.
JSON.stringify is the way out: data becomes text. JSON.parse is the way back in.
Out is safe, because the compiler checked your data. In is not: the text could hold anything. The plan is parse, check, and only then use.
type Item = { name: string; qty: number };
const items: Item[] = [
{ name: "pen", qty: 3 },
];
const text = JSON.stringify(items);
console.log(text);
// [{"name":"pen","qty":3}]Concept
Three questions
To trust an unknown value, ask in order.
Is it an object? Is it not null? (typeof says "object" for null too, an old quirk.) Does it have the key? "qty" in v answers that.
Then one more: is the value under that key the right type? After that the compiler knows it is a number.
function qty(v: unknown): number | null {
if (typeof v !== "object") return null;
if (v === null) return null;
if (!("qty" in v)) return null;
const q = v.qty;
return typeof q === "number" ? q : null;
}
console.log(qty({ qty: 3 }), qty("pen"));
// 3 null10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.