Turn Environment Variables into Typed Config

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write parseEnv(source, spec): source holds environment variables as strings (or undefined), and spec describes each variable to read as { type, default? }, where type is string, number or boolean. Return an object with just the spec's variables, converted: numbers must be finite, booleans are true, false, 1 or 0, and a missing or empty variable takes its default. Throw for one with no default, or a value that doesn't convert. Type it so the result has each variable's own type, a default must match its type, and an unknown type is rejected.

Your code must pass

  • Converts numbers, booleans and strings
  • Uses defaults for missing values
  • Throws for missing or invalid values
  • Has no type errors
  • Config has each variable's type
  • Default must match the variable's type
  • Rejects an unknown type