Any Standard Schema (Zod, Valibot, ArkType, and others) can be used directly as a flag type. type-flag detects the schema, validates the value, and infers the flag type from the schema's output. No wrapper or extra import.
import * as z from 'zod'import { typeFlag } from 'type-flag'const parsed = typeFlag({ size: z.enum(['small', 'medium', 'large']), port: z.coerce.number(), tags: [z.string()] // wrap in an array to accept multiple})parsed.flags.size // 'small' | 'medium' | 'large' | undefinedparsed.flags.port // number | undefinedparsed.flags.tags // string[]
It is library-agnostic, so any compliant schema works the same way:
import * as v from 'valibot'const parsed = typeFlag({ mode: v.picklist(['dev', 'prod'])})parsed.flags.mode // 'dev' | 'prod' | undefined
Schemas work everywhere a flag type is accepted, including arrays ([z.string()]), { type, default } objects, and getFlag. On validation failure, the schema's message is surfaced through type-flag's error wrapping as Flag "<flag>": <message>, where <flag> is the flag's canonical spelling, such as --size or -x. This adds no runtime dependency: the Standard Schema spec is types-only and vendored in.
A few things to keep in mind:
Numbers need coercion. CLI values are always strings, so z.number() rejects "3000". Use z.coerce.number() (or your library's equivalent), then chain validators like .int(), .min(), and .max().
For multiple values, wrap the schema in [ ] (as with tags above), not z.array(...). A schema that itself outputs an array validates a single CLI token against the array, so it type-checks but throws at runtime. To split one value into an array, use a transform such as z.string().transform(value => value.split(',')).
Keep booleans native. Use Boolean rather than a schema for boolean flags, so valueless --flag, --no-flag negation, and short-flag grouping keep working.
Use type-flag's default. type-flag only runs the parser when a flag is present, so a schema-level .default() never fires for an absent flag. Set default on the flag instead.
Schemas must be synchronous. Flag parsing is synchronous, so an async schema throws.
Multiple Values
Wrap a parser function in an array to collect repeated values.
Unknown flags are not converted to camelCase to allow for accurate error handling.
Wrapper CLIs often need to consume their own flags and pass everything else to another command. If you pass your own argv array, type-flag removes parsed tokens and leaves ignored tokens behind.
Do not group flags you parse with flags another parser will read. Ignored tokens are left in argv, so an ignore callback can stop parsing at a command name and preserve the full command tail for another parser. When a defined value-taking flag is ignored, its following value is also left in argv and is not passed to ignore. If other aliases in the same group are parsed, they are deleted in place. A remainder of exactly -- is removed, because most parsers, including type-flag, would read it as the end-of-flags delimiter and stop parsing the rest of argv.
Use the --target-flag=value form for forwarded unknown flags with values. Since type-flag does not know whether an unknown flag takes a value, it parses a separate following token on its own, usually as an argument.
Do not group an extracted short flag with flags another parser will handle. Extracting part of a group deletes those characters in place and keeps an attached value only if the original last character remains. A remainder of exactly -- is removed; all others are kept in order. The next parser may interpret them differently:
Extracting -q from -q-abc leaves the long flag --abc; -q? leaves the positional -?.
Extracting -q from ['--name', '-q5x'] leaves -5x. A later type-flag parser consumes it as the value of name: String unless both 5 and x are defined flags.
Extracting -q from -q-=value leaves --=value, which type-flag treats as a positional. Node's util.parseArgs reads it as an unknown long option named =value.
Which flag takes the next token also depends on the next parser. For example, extracting -b from ['-ab', 'file'] leaves ['-a', 'file'], so a later parser with a: String consumes file.
You can also stop parsing after the first positional argument:
Arguments are values that are not associated with a flag. They are stored in _.
Everything after the first -- is treated as an argument and is also stored in _['--']. The -- sentinel itself is omitted; later -- tokens are ordinary arguments inside _['--'].
For ['one', '--', 'two'], parsed._.slice() is ['one', 'two'] and parsed._['--'] is ['two'].
Parser and framework integrations that need to rebuild this shape can use createPositionalArguments(); see the API reference below.
Ordered Entries
[!NOTE]
Advanced. Most CLIs only need flags. Reach for entries when the order of operations across different flags matters.
flags groups values by flag name, which discards how occurrences of different flags interleaved on the command line. entries is the ordered stream of every interpreted argv element, so that relative order is preserved.
flag — a flag defined in the schema (it landed in flags). name is the canonical schema key (regardless of whether the alias, kebab-case, or camelCase form was used), and value is the parsed value for that single occurrence.
unknown-flag — a flag not in the schema. name is the raw argv name; value is the explicit value or true.
argument — a positional value.
Only parsed elements appear. Tokens after the -- delimiter are not parsed, so they are excluded from entries — find them in _['--'].
This is useful for curl-style data assembly (-d / --data-urlencode joined in argv order), debugging "which occurrence won", or any CLI where flags are an ordered instruction log rather than independent settings.
Value Delimiters
The characters =, :, and . delimit a value from a flag.
These are the supported delimiters; arbitrary delimiter characters are not treated as value separators.
Error Wrapping
When a custom type parser (or Standard Schema) throws, the error is wrapped in a FlagParseError whose message identifies the flag by name. The original error is preserved on .cause, and the flag name on .flagName.
For typeFlag, .flagName is the schema key, regardless of the spelling used. The message uses the kebab-case long flag (for example, --org-id for orgId), or the short flag for a single-character key. For getFlag, .flagName is the first long search name without dashes, or the first short name if there is no long name. The message uses that search name with its dashes.
FlagParseError extends TypeError, so existing instanceof TypeError checks keep working while instanceof FlagParseError lets you handle a bad flag value precisely.
The --no- prefix only applies to flags defined as Boolean. For non-boolean or unregistered flags, --no-<name> is treated as an unknown flag.
A negated flag with an explicit value, such as --no-verbose=false, is also unknown unless no-verbose is itself defined. Defined flags take precedence over negation.
You can also pass false explicitly with a value delimiter:
Explicit Boolean values must be exactly true or false, including for [Boolean]. Values are case-sensitive; any other value, including an empty value, throws FlagParseError. This applies to =, :, and . delimiters and short aliases in both typeFlag and getFlag.
Use a single-character name when the short form is the flag (-x/-y coordinates, -h vs --help). Use an alias when --verbose and -v should set the same value.
A single-character flag cannot have an alias.
getFlag()
Use getFlag() when you only need one typed flag and want to leave the rest of argv available for another parser or command.
By default, getFlag() returns the last matching value and removes every matching occurrence from argv. Wrap the parser in an array to retrieve all matching values.
An object containing flag schema definitions. The key is the flag name, and the value is either a parser function, an array parser, or an object containing the parser plus options.
argv
Type: string[]
Default: process.argv.slice(2)
The argv array to parse. If you pass your own array, it is mutated to remove parsed flags and arguments.
A comma-separated list of flag names to parse, such as -p, --port. Whitespace around each name is ignored. A short name has one dash and one UTF-16 code unit that is a Unicode letter, Unicode number, or _. A long name has two dashes, starts with that same character class, and has at least two UTF-16 code units after the dashes. One supplementary character, such as 𐐀, qualifies. Long names cannot contain whitespace, =, :, or .. Short names match short flags and groups, while long names match only long flags. Invalid names throw an Error.
A function to parse the flag value. Wrap the function in an array to retrieve all values.
argv
Type: string[]
Default: process.argv.slice(2)
The argv array to parse. If you pass your own array, it is mutated to remove every matching flag and its value.
createPositionalArguments(argv)
Builds the same positional argument shape returned as parsed._. This is mainly useful for parser or framework integrations that already preserved an argv tail and need to expose type-flag-compatible positionals.
That one schema owns the app key, parser, alias, default, and TypeScript output. This is the main reason to choose type-flag: less post-processing, fewer raw option strings in app code, and a parsed result shaped like your application.
Quick permissive parsing for scripts where heuristic coercion is acceptable; TypeScript users rely on separate broad @types/minimist types.
Explicit schemas with bundled, schema-inferred TypeScript output.
Cleye, commander, yargs, cac, meow
Full CLI apps that need commands, help text, version flags, validation UX, or app structure.
Focused flag parsing that stays small and easy to embed.
A few trade-offs are intentional:
It does not parse POSIX-style short string values like -ovalue.
It treats missing string values as ""; strict parsers like parseArgs() and arg throw.
Values that start with - and a digit are accepted after a value-taking flag: --count -1, --range -5..10, --delta -5%. A token whose characters are all defined flags (e.g. -1 when 1 is an alias) is treated as those flags, so use --count=-1 for it. A standalone -5 (not after a value-taking flag) and -Infinity also need the = form.
Agent Skills
This package ships with a built-in agent skill for AI coding assistants. Set up skills-npm in your project to use it.