Skip to content
dreamcode
dreamcode
Peaks
Config Gatekeeper
AdvancedTypeScript
Reward: +80 XP
PROBLEM

Config Gatekeeper

Data from outside your program (a file, a request, a form) arrives as unknown. Write parseConfig(input: unknown): Result that checks it before anything trusts it.

A valid config is an object with:

  • host: a non-empty string
  • port: a whole number from 1 to 65535
  • debug: an optional boolean that defaults to false

Return { ok: true, value: { host, port, debug } } (only those three keys) when it is valid. Otherwise return { ok: false, error } with the first problem found, checking in this order: "config must be an object", "host must be a non-empty string", "port must be a whole number from 1 to 65535", "debug must be a boolean".

Examples
parseConfig({ host: "sky.local", port: 8080 })
{ ok: true, value: { host: "sky.local", port: 8080, debug: false } }
parseConfig({ host: "a", port: 1, debug: true, secret: "x" })
{ ok: true, value: { host: "a", port: 1, debug: true } }
solution.ts
TYPESCRIPT
Saved as you type

Tests

0 of 8 passing
  • valid, debug defaults
    parseConfig({ host: "sky.local", port: 8080 })
    expected { ok: true, value: { host: "sky.local", port: 8080, debug: false } }
  • extra keys are dropped
    parseConfig({ host: "a", port: 1, debug: true, secret: "x" })
    expected { ok: true, value: { host: "a", port: 1, debug: true } }
  • not an object
    parseConfig("localhost:80")
    expected { ok: false, error: "config must be an object" }
  • null is not a config
    parseConfig(null)
    expected { ok: false, error: "config must be an object" }
  • empty host
    parseConfig({ host: "", port: 80 })
    expected { ok: false, error: "host must be a non-empty string" }
  • port out of range
    parseConfig({ host: "a", port: 70000 })
    expected { ok: false, error: "port must be a whole number from 1 to 65535" }
  • port as text
    parseConfig({ host: "a", port: "80" })
    expected { ok: false, error: "port must be a whole number from 1 to 65535" }
  • debug as text
    parseConfig({ host: "a", port: 80, debug: "yes" })
    expected { ok: false, error: "debug must be a boolean" }
On the line
+80 XP
Pass all 8 tests to claim it.