Skip to content
dreamcode
dreamcode
Map
unknown & never
Lesson 19 of 26
+15 XP on finish
TS ADVANCEDChapter 3 · TS Advanced

unknown and never

any switches type checking off. unknown is its safe twin: a value you must check before you can use it, which makes it the right type for anything from outside your program, like parsed JSON. never is the type of something that cannot happen: a function that always throws returns never, and a value narrowed until no options are left has type never.

Worked example

How it reads

  • Each typeof check unlocks the methods of that one type
  • fail never returns normally, so its return type is never
  • A caught error is unknown too, so check or cast it before reading .message
Cloud tip: Type data at the boundary: accept unknown, validate it once, and pass a precise type to the rest of your code.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Narrow raw safely: check it is a non-null object that has a string name, then log the name: Nova.

Press Run to check your work.