Lesson 10 of 10

The unknown type instead of any

Goal

Check a value before you use it

01

Explanation

The any type switches off the compiler's checks: every operation on it is allowed, and every mistake slips through to runtime. JSON.parse returns any, so data from the outside world enters your code unchecked. Run the starter code and look at 30001: the port number arrived as a string, so the addition turned into string concatenation.

unknown is the opposite. It accepts any value, but it won't allow any operation on it until you've confirmed its type. You use typeof, !== null and in to narrow the type step by step until the value is safe to use.

Watch out for a common mistake: typeof null === "object", so checking typeof data === "object" on its own isn't enough before you read a property from the value.

02

Your task

Make safeParse return unknown, then narrow the result's type in portFrom so that it returns port if it's a number, and 8080 in every other case.

Checks

6 checks
  1. No type errors
  2. safeParse's result can't be used before it's checked
  3. safeParse's result can be used after narrowing
  4. portFrom reads the port when it's a number
  5. A port given as a string returns 8080
  6. portFrom doesn't crash on null
03

Hints

0/3
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.