Command Palette

Search for a command to run...

Hectal
Phase 15: TypeScript in Real Projects
TypeScript · Exercise 5 of 6 PreviousNext
Intermediate

Validate data at the boundary

JSON.parse gives any. Write parseUser(text: string): User | undefined that returns the user only if the data really is an object with a string name and a number age, without any as User cast and without any.

The program prints the result for three inputs. A good user prints Asha 30, a user with text for the age prints invalid, and non-JSON-object text [] prints invalid.

What Check tests

  1. Your code has no type errors
  2. The program prints Asha 30, invalid, invalid
  3. No type cast to User
  4. No any
  5. parseUser returns User or undefined

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Console

Nothing printed yet.