Lesson 10 of 10
The unknown type instead of any
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Check a value before you use it
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.
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- No type errors
- safeParse's result can't be used before it's checked
- safeParse's result can be used after narrowing
- portFrom reads the port when it's a number
- A port given as a string returns 8080
- portFrom doesn't crash on null