Skip to the solution
EasyFrontend9 min read

What is the difference between any and unknown?

759 views

The problem

Question presented to candidate: "Both `any` and `unknown` can hold any value. So what is the difference, and which one would you use for the result of `JSON.parse` or for a caught error?"

What a strong answer should cover:

  • Both are top types for assignment: every value can be assigned to either
  • `any` disables checking: every property access, call and assignment compiles, and it is contagious (whatever you read from it is `any` too)
  • `unknown` is the safe top type (added in TypeScript 3.0): you must narrow it with `typeof`, `instanceof`, `Array.isArray`, `in` or a type guard before using it, and it is assignable only to `unknown` and `any`
  • Practical uses: `unknown` for untrusted input (`JSON.parse`, network data, catch variables under `strict`), `any` only as a temporary migration escape hatch
  • Type algebra: `unknown | T` is `unknown`, `unknown & T` is `T`, `keyof unknown` is `never`

Code / implementation expected: Yes β€” the same operation on `any` and `unknown`, and a narrowing function that accepts `unknown`.

  • any
  • unknown

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptany compiles anything, unknown must be narrowed
TypeScriptType algebra, contagious any, JSON.parse and catch variables

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 5 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What are the basic types in TypeScript?

Continue