Stop writing if statements for your CLI flags
25 points by hongminhee
25 points by hongminhee
These libraries infer types for individual options. --port is a number. --verbose is a boolean
Unless I've misunderstood what you mean by this, inferring types based on named is a horrifying type of automagic. If you're using a CLI option parser, then the option description DSL is part of your documentation and should be explicit.
Look at the examples ;)
Maybe inferred is the wrong word cause you define it, but some inference is happening because you don't explicitly write the type.
you don't explicitly write the type.
How do you not explicitly write the type in
{ outputFile: string; openBrowser: boolean }
or
port: withDefault(option("--port", integer()), 5432),
?
That string isn’t a type (note that it’s in a value position), it’s a Type<From, To>, which I think would be better named Codec or maybe Coercion. The actual TypeScript type of port is what is being inferred. There can be many Types that have a string-typed output; that one is just the identity function (Type<string, string>).
A better example would be DateFromISOString or the like.
That’s a distinction without a difference. You’re explicitly telling the parser what output type you’re looking for.
You’re also telling it what input format you’re using. The TS type is a side effect of that intention. It’s setting up a transformation pipeline from string to whatever, not just setting a bare type.
Stop nitpicking. The point is inference is happening. The parser isn't using a TS type as input.
Sure, some level of inference might be happening, but it's much less magical than inferring the type based on the name of the option, as the grandparent comment thought. Clarifying that distinction is not nitpicking, IMO.
While I like the ideas expressed, I'm not sure that it's clear that this is largely a plug for the author's own library for doing CLI parsing.
Good stuff 👍 You can also feed the parsed options and env vars into a Zod-like schema and get descriptive and familiar error messages for free.
This is a nice pattern! I usually only do the second part with a match-lambda on a parsed args object, but I can totally see how flipping the script slightly and generating the parser using the match tree could be even more ergonomic and type safe.