Command Palette

Search for a command to run...

Hectal
Phase 17: Interviews and Capstone
TypeScript · Exercise 4 of 6 PreviousNext
Intermediate

Review: Fix the any Leak

This function compiles, but it is dangerous: JSON.parse returns any, so parseConfig promises a Config it never checked. The program below prints ok for a config whose port is the text "8080".

Fix parseConfig so that it takes the parsed value as unknown, checks that port is a number and host is a string, and throws an Error otherwise. The program must then print ok localhost:8080, rejected, rejected.

Do not use the word for the unchecked type, and do not use type assertions with the as keyword. Do not change the loop at the bottom.

What Check tests

  1. Your code has no type errors
  2. A valid config is accepted
  3. A config with a text port is rejected
  4. Broken JSON is rejected
  5. The result is still typed as Config
  6. No unchecked type and no assertions

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.