typescript · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
means: check me before you use me.
any trusts everything. unknown trusts nothing. A value labelled unknown can hold anything, but the checker will not let you use it until you narrow it. Try data.length on an unknown value and you get TS18046: data is of type unknown.
turns JSON text into values, and like json() it gives any. Label the result unknown instead, then check it: typeof data === "string" for a string, or Array.isArray(data) for an array.
Each check narrows the value, and inside it the checker lets you go ahead.
const data: unknown = JSON.parse('["tea", "cake"]');
if (Array.isArray(data)) {
console.log(`A list of ${data.length} items`);
}
const word: unknown = JSON.parse('"hello"');
if (typeof word === "string") {
console.log(word.toUpperCase());
} Single quotes work like double quotes. They are handy when the text holds double quotes, as JSON does.
guess first
Using an unknown value too early. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const reply: unknown = JSON.parse('{"score": 12}');
console.log("Got a reply");
console.log(reply.score + 1);
your turn
Your turn. Check before you count.
Fill in the check so the code only counts the items when the parsed value really is an array. Then try changing the JSON text to something else.
fix it
The checker will not trust the temperature. Fix it!
- Read the error:
TS18046: 'parsed' is of type 'unknown'.The checker will not do maths with it. - Narrow it first: check that
typeof parsedis"number", and do the maths inside that check. - Wrap line 2 in
if (typeof parsed === "number") { }, then press run.
nailed it
you check before you trust. :D
unknowncan hold anything, but cannot be used unchecked.JSON.parseturns JSON text into values.- Narrow with
typeoforArray.isArraybefore using it.
new words in your collection
- unknown
- JSON.parse
This lesson isn’t saved. A free account remembers every lesson you finish.