Lesson 7 of 10
Type guards
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
From unknown to a type you can trust
Explanation
Whatever you get from JSON.parse or from the network has no type you actually know, so its honest type is unknown, and the compiler won't let you use it until you check it.
The check itself narrows the type. After typeof x === "object" && x !== null, x is an object, and after "id" in x it has an id field. But that field's type stays unknown until you check it with typeof as well.
This narrowing stops at the edge of the function, though. A function that returns boolean tells its caller nothing about the type. The return type x is User carries that knowledge outside, so data is a User inside if (isUser(data)). A function like this is called a type guard, and it's a promise the compiler doesn't verify: if it always returned true, the compiler would believe it.
Your task
Write isUser(x: unknown): x is User so it really checks that id is a number and email is a string, and returns false for null and for primitive values without throwing.
Checks
5 checks- No type errors
- Accepts a valid user
- Rejects null and primitive values without throwing
- Rejects an object with missing fields or fields of the wrong type
- Inside if (isUser(v)), v is a User