×

typescript · level 2 · unit 7 · lesson 1

  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

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.