← All Exercises

Parse CLI Flags and Commands

basicjavascript~25min

Background

CLI tools that silently ignore unknown flags hide typos in automation. Explicit parse errors make scripts fail loudly instead of doing the wrong thing.

Problem

Parse argv against a flag spec, separating boolean and string flags from the command, and report unknown flags and missing values.

Input

JSON object: { argv: string[], spec: { flags: { [name]: "bool"|"string" }, commands: string[] } }

Output

JSON object: { flags, command, errors: string[] }

Sample tests

Sample 1

Input: {"argv":["--verbose","--out=dist","build"],"spec":{"flags":{"verbose":"bool","out":"string"},"commands":["build"]}}
Expected: {"flags":{"verbose":true,"out":"dist"},"command":"build","errors":[]}

Sample 2

Input: {"argv":["--nope","--out"],"spec":{"flags":{"out":"string"},"commands":["build"]}}
Expected: {"flags":{},"command":null,"errors":["missing-value:out","unknown-flag:nope"]}

Your solution

Learning objective

Build CLI parsing that rejects typos instead of ignoring them.