Hone

Lessons · TypeScript · any vs unknown

any switches checking off; unknown makes you prove it

any lets you do anything, silently. unknown lets you do nothing until you check what it is.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

JSON.parse, fetch results, user input: things of genuinely unknown shape. Typing them unknown forces the validation that keeps bad data out of the rest of the program.

How to think about it

Do I actually know this value's shape yet? Never write any by choice. Type external data as unknown, then narrow: typeof, 'in', Array.isArray, or a validation function that returns a typed value.

Worked example

const data: unknown = JSON.parse(text);
Could be anything.
if (typeof data === "object" && data !== null && "id" in data) {
Prove it step by step.
  console.log((data as { id: unknown }).id);
Only now touch id, still unknown itself.
}

Your turn

Type the parsed value honestly.

const raw:  = JSON.parse(body);

The trap

Reaching for any 'just to make it compile'. Every any is a place where a bug will not be caught.

Practise any vs unknown on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.