Skip to content

Coerce helpers

coerce turns the raw terminal string into the type that the schema expects. TypeScript checks that the two agree. A mismatched helper is a compile error.

import { coerce } from "@staticbolt/args-parser";
Helper Produces Notes
coerce.string string Does nothing. Can be omitted for string schemas.
coerce.number number
coerce.bigint bigint
coerce.boolean boolean Makes the option a flag that takes no value and accepts --no-.
coerce.json anything JSON.parse of the input. Accepts dotted keys.
coerce.object(options?) object JSON.parse plus optional per-value conversions. Accepts dotted keys.
coerce.stringArray(sep) string[] Splits on sep. Repeatable.
coerce.numberArray(sep) number[] Splits on sep. Repeatable.
coerce.booleanArray(sep) boolean[] Splits on sep. Repeatable.
coerce.stringSet(sep) Set<string> Splits on sep. Repeatable, duplicates removed.
coerce.numberSet(sep) Set<number> Splits on sep. Repeatable, duplicates removed.
coerce.booleanSet(sep) Set<boolean> Splits on sep. Repeatable, duplicates removed.

Repeatable means you can pass the option more than once. The parser merges the results before validation. See Repeatable options.

A helper that cannot convert its input fails with ValidationErrorCode.CoercionFailed.

ObjectCoerceMethodOptions

Passed to coerce.object. Each conversion runs after the JSON parse, and takes true for every value or a list of dotted paths to limit it. A value that fails to convert stays the original string.

Option Type Converts
coerceBoolean boolean | string[] "true" and "false", lowercase only, to booleans.
coerceNumber boolean | string[] Number-like strings to numbers, including -1.5 and +2.
coerceBigint boolean | string[] Integer-like strings to bigint.
coerceDate boolean | string[] Date-like strings to Date.
coerce.object({ coerceNumber: true });
coerce.object({ coerceBoolean: true, coerceNumber: ["port", "credentials.retries"] });

See Object options.

Writing your own

A coerce function takes the terminal string and returns the schema's output type. That is the whole contract.

const toUpperCase = (input: string) => input.toUpperCase();
const cli = defineCLI({
cliName: "example",
options: {
name: { schema: z.string(), coerce: toUpperCase },
},
});

Throw a CliError when the input cannot be converted, and the parser reports it like any other coercion failure.

The optional type property on the function tells the parser how the flag behaves on the command line:

type Effect
"boolean" The flag takes no value, and --no- negation works.
"object" The flag accepts JSON and dotted keys such as --option.key=value.
not set The flag takes a value, and that value is passed to your function.
const toFlag = (input: string) => input === "true";
toFlag.type = "boolean";

Returning an array or a set is what makes an option repeatable. You do not need a type for that.