@types/yargs
- Version 17.0.33
- Published
- 60.4 kB
- 1 dependency
- MIT license
Install
npm i @types/yargs
yarn add @types/yargs
pnpm add @types/yargs
Overview
TypeScript definitions for yargs
Index
Variables
Interfaces
Argv
- alias()
- argv
- array()
- boolean()
- check()
- choices()
- coerce()
- command()
- commandDir()
- completion()
- config()
- conflicts()
- count()
- default()
- demand()
- demandCommand()
- demandOption()
- deprecateOption()
- describe()
- detectLocale()
- env()
- epilog()
- epilogue()
- example()
- exit()
- exitProcess()
- fail()
- getCompletion()
- getHelp()
- global()
- group()
- help()
- hide()
- implies()
- locale()
- middleware()
- nargs()
- normalize()
- number()
- onFinishCommand()
- option()
- options()
- parse()
- parseAsync()
- parsed
- parserConfiguration()
- parseSync()
- pkgConf()
- positional()
- recommendCommands()
- require()
- required()
- requiresArg()
- scriptName()
- showCompletionScript()
- showHelp()
- showHelpOnFail()
- showHidden()
- showVersion()
- skipValidation()
- strict()
- strictCommands()
- strictOptions()
- string()
- terminalWidth()
- updateLocale()
- updateStrings()
- usage()
- version()
- wrap()
Type Aliases
- Alias
- Arguments
- ArgumentsCamelCase
- AsyncCompletionFunction
- BuilderArguments
- BuilderCallback
- CamelCase
- CamelCaseKey
- Choices
- CommandBuilder
- CompletionCallback
- Defined
- FallbackCompletionFunction
- InferredOptionType
- InferredOptionTypeInner
- InferredOptionTypePrimitive
- InferredOptionTypes
- IsAny
- IsRequiredOrHasDefault
- IsUnknown
- MiddlewareFunction
- Omit
- ParseCallback
- ParserConfigurationOptions
- PascalCase
- PositionalOptionsType
- PromiseCompletionFunction
- SyncCompletionFunction
- ToArray
- ToNumber
- ToString
Variables
variable yargs
var yargs: yargs.Argv<{}>;
Interfaces
interface Argv
interface Argv<T = {}> {}
The type parameter
T
is the expected shape of the parsed options.Arguments<T>
is those options plus_
and$0
, and an indexer falling back tounknown
for unknown options.For the return type /
argv
property, we create a mapped type overArguments<T>
to simplify the inferred type signature in client code.
property argv
argv: | { [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; } | Promise<{ [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }>;
Get the arguments as a plain old object.
Arguments without a corresponding flag show up in the
argv._
array.The script name or node command is available at
argv.$0
similarly to how$0
works in bash or perl.If
yargs
is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js), it will ignore the first parameter since it expects it to be the script name. In order to override this behavior, use.parse(process.argv.slice(1))
instead of .argv and the first parameter won't be ignored.
property parsed
parsed: DetailedArguments | false;
If the arguments have not been parsed, this property is
false
.If the arguments have been parsed, this contain detailed parsed arguments.
method alias
alias: { <K1 extends keyof T, K2 extends string>( shortName: K1, longName: K2 | readonly K2[] ): Argv<T & { [key in K2]: T[K1] }>; <K1 extends keyof T, K2 extends string>( shortName: K2, longName: K1 | readonly K1[] ): Argv<T & { [key in K2]: T[K1] }>; ( shortName: string | readonly string[], longName: string | readonly string[] ): Argv<T>; (aliases: { [shortName: string]: string | readonly string[] }): Argv<T>;};
Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
Optionally
.alias()
can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
method array
array: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: ToArray<T[key]> } >; <K extends string>(key: K | readonly K[]): Argv< T & { [key in K]: (string | number)[] } >;};
Tell the parser to interpret
key
as an array. If.array('foo')
is set,--foo foo bar
will be parsed as['foo', 'bar']
rather than as'foo'
. Also, if you use the option multiple times all the values will be flattened in one array so--foo foo --foo bar
will be parsed as['foo', 'bar']
When the option is used with a positional, use
--
to tellyargs
to stop adding values to the array.
method boolean
boolean: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: boolean } >; <K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: boolean }>;};
Interpret
key
as a boolean. If a non-flag option followskey
inprocess.argv
, that string won't get set as the value ofkey
.key
will default tofalse
, unless adefault(key, undefined)
is explicitly set.If
key
is an array, interpret all the elements as booleans.
method check
check: ( func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean) => Argv<T>;
Check that certain conditions are met in the provided arguments.
Parameter func
Called with two arguments, the parsed
argv
hash and an array of options and their aliases. Iffunc
throws or returns a non-truthy value, show the thrown error, usage information, and exit.Parameter global
Indicates whether
check()
should be enabled both at the top-level and for each sub-command.
method choices
choices: { <K extends keyof T, C extends readonly any[]>(key: K, values: C): Argv< Omit<T, K> & { [key in K]: C[number] } >; <K extends string, C extends readonly any[]>(key: K, values: C): Argv< T & { [key in K]: C[number] } >; <C extends { [key: string]: readonly any[] }>(choices: C): Argv< Omit<T, keyof C> & { [key in keyof C]: C[key][number] } >;};
Limit valid values for key to a predefined set of choices, given as an array or as an individual value. If this method is called multiple times, all enumerated values will be merged together. Choices are generally strings or numbers, and value matching is case-sensitive.
Optionally
.choices()
can take an object that maps multiple keys to their choices.Choices can also be specified as choices in the object given to
option()
.
method coerce
coerce: { <K extends keyof T, V>(key: K | readonly K[], func: (arg: any) => V): Argv< Omit<T, K> & { [key in K]: V } >; <K extends string, V>(key: K | readonly K[], func: (arg: any) => V): Argv< T & { [key in K]: V } >; <O extends { [key: string]: (arg: any) => any }>(opts: O): Argv< Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> } >;};
Provide a synchronous function to coerce or transform the value(s) given on the command line for
key
.The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error. The returned value will be used as the value for
key
(or one of its aliases) inargv
.If the function throws, the error will be treated as a validation failure, delegating to either a custom
.fail()
handler or printing the error message in the console.Coercion will be applied to a value after all other modifications, such as
.normalize()
.Optionally
.coerce()
can take an object that maps several keys to their respective coercion function.You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to
.coerce()
.If you are using dot-notion or arrays, .e.g.,
user.email
anduser.password
, coercion will be applied to the final object that has been parsed
method command
command: { <U = T>( command: string | readonly string[], description: string, builder?: BuilderCallback<T, U>, handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>, middlewares?: Array<MiddlewareFunction<U>>, deprecated?: boolean | string ): Argv<T>; <O extends { [key: string]: Options }>( command: string | readonly string[], description: string, builder?: O, handler?: ( args: ArgumentsCamelCase<InferredOptionTypes<O>> ) => void | Promise<void>, middlewares?: MiddlewareFunction<O>[], deprecated?: string | boolean ): Argv<T>; <U = any>( command: string | readonly string[], description: string, module: CommandModule<T, U> ): Argv<T>; <U = T>( command: string | readonly string[], showInHelp: false, builder?: BuilderCallback<T, U>, handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void>, middlewares?: MiddlewareFunction<U>[], deprecated?: string | boolean ): Argv<T>; <O extends { [key: string]: Options }>( command: string | readonly string[], showInHelp: false, builder?: O, handler?: ( args: ArgumentsCamelCase<InferredOptionTypes<O>> ) => void | Promise<void> ): Argv<T>; <U = any>( command: string | readonly string[], showInHelp: false, module: CommandModule<T, U> ): Argv<T>; <U = any>(module: CommandModule<T, U>): Argv<T>; <U = any>(modules: CommandModule<T, U>[]): Argv<T>;};
Define the commands exposed by your application.
Parameter command
Should be a string representing the command or an array of strings representing the command and its aliases.
Parameter description
Use to provide a description for each command your application accepts (the values stored in
argv._
). Setdescription
to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion.Parameter builder
Object to give hints about the options that your command accepts. Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help.
Note that when
void
is returned, the handlerargv
object type will not include command-specific arguments.Parameter handler
Function, which will be executed with the parsed
argv
object.
method commandDir
commandDir: (dir: string, opts?: RequireDirectoryOptions) => Argv<T>;
Apply command modules from a directory relative to the module calling this method.
method completion
completion: { (): Argv<T>; (cmd: string, func?: AsyncCompletionFunction): Argv<T>; (cmd: string, func?: SyncCompletionFunction): Argv<T>; (cmd: string, func?: PromiseCompletionFunction): Argv<T>; (cmd: string, func?: FallbackCompletionFunction): Argv<T>; ( cmd: string, description?: string | false, func?: AsyncCompletionFunction ): Argv<T>; ( cmd: string, description?: string | false, func?: SyncCompletionFunction ): Argv<T>; ( cmd: string, description?: string | false, func?: PromiseCompletionFunction ): Argv<T>; ( cmd: string, description?: string | false, func?: FallbackCompletionFunction ): Argv<T>;};
Enable bash/zsh-completion shortcuts for commands and options.
If invoked without parameters,
.completion()
will make completion the command to output the completion script.Parameter cmd
When present in
argv._
, will result in the.bashrc
or.zshrc
completion script being outputted. To enable bash/zsh completions, concat the generated script to your.bashrc
or.bash_profile
(or.zshrc
for zsh).Parameter description
Provide a description in your usage instructions for the command that generates the completion scripts.
Parameter func
Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method.
method config
config: { (): Argv<T>; ( key: string | readonly string[], description?: string, parseFn?: (configPath: string) => object ): Argv<T>; ( key: string | readonly string[], parseFn: (configPath: string) => object ): Argv<T>; (explicitConfigurationObject: object): Argv<T>;};
Tells the parser that if the option specified by
key
is passed in, it should be interpreted as a path to a JSON config file. The file is loaded and parsed, and its properties are set as arguments. Because the file is loaded using Node's require(), the filename MUST end in.json
to be interpreted correctly.If invoked without parameters,
.config()
will make --config the option to pass the JSON config file.Parameter description
Provided to customize the config (
key
) option in the usage string.Parameter explicitConfigurationObject
An explicit configuration
object
method conflicts
conflicts: { (key: string, value: string | readonly string[]): Argv<T>; (conflicts: { [key: string]: string | readonly string[] }): Argv<T>;};
Given the key
x
is set, the keyy
must not be set.y
can either be a single string or an array of argument names thatx
conflicts with.Optionally
.conflicts()
can accept an object specifying multiple conflicting keys.
method count
count: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: number } >; <K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number }>;};
Interpret
key
as a boolean flag, but set its parsed value to the number of flag occurrences rather thantrue
orfalse
. Default value is thus0
.
method default
default: { <K extends keyof T, V>(key: K, value: V, description?: string): Argv< Omit<T, K> & { [key in K]: V } >; <K extends string, V>(key: K, value: V, description?: string): Argv< T & { [key in K]: V } >; <D extends { [key: string]: any }>(defaults: D, description?: string): Argv< Omit<T, keyof D> & D >;};
Set
argv[key]
tovalue
if no option was specified inprocess.argv
.Optionally
.default()
can take an object that maps keys to default values.The default value can be a
function
which returns a value. The name of the function will be used in the usage string.Optionally,
description
can also be provided and will take precedence over displaying the value in the usage instructions.
method demand
demand: { <K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv< Defined<T, K> >; <K extends string>(key: K | readonly K[], msg?: string | true): Argv< T & { [key in K]: unknown } >; (key: string | readonly string[], required?: boolean): Argv<T>; (positionals: number, msg: string): Argv<T>; (positionals: number, required?: boolean): Argv<T>; (positionals: number, max: number, msg?: string): Argv<T>;};
Deprecated
since version 6.6.0 Use '.demandCommand()' or '.demandOption()' instead
method demandCommand
demandCommand: { (): Argv<T>; (min: number, minMsg?: string): Argv<T>; (min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>;};
Demand in context of commands. You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
method demandOption
demandOption: { <K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv< Defined<T, K> >; <K extends string>(key: K | readonly K[], msg?: string | true): Argv< T & { [key in K]: unknown } >; (key: string | readonly string[], demand?: boolean): Argv<T>;};
Parameter key
If is a string, show the usage information and exit if key wasn't specified in
process.argv
. If is an array, demand each element.Parameter msg
If string is given, it will be printed when the argument is missing, instead of the standard error message.
Parameter demand
Controls whether the option is demanded; this is useful when using .options() to specify command line parameters.
method deprecateOption
deprecateOption: (option: string, msg?: string) => Argv<T>;
Shows a [deprecated] notice in front of the option
method describe
describe: { (key: string | readonly string[], description: string): Argv<T>; (descriptions: { [key: string]: string }): Argv<T>;};
Describe a
key
for the generated usage information.Optionally
.describe()
can take an object that maps keys to descriptions.
method detectLocale
detectLocale: (detect: boolean) => Argv<T>;
Should yargs attempt to detect the os' locale? Defaults to
true
.
method env
env: { (): Argv<T>; (prefix: string): Argv<T>; (enable: boolean): Argv<T> };
Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments.
Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo)
If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv.
Program arguments are defined in this order of precedence: 1. Command line args 2. Env vars 3. Config file/objects 4. Configured defaults
Env var parsing is disabled by default, but you can also explicitly disable it by calling
.env(false)
, e.g. if you need to undo previous configuration.
method epilog
epilog: (msg: string) => Argv<T>;
A message to print at the end of the usage instructions
method epilogue
epilogue: (msg: string) => Argv<T>;
A message to print at the end of the usage instructions
method example
example: { (command: string, description: string): Argv<T>; (command: readonly [string, string?][]): Argv<T>;};
Give some example invocations of your program. Inside
cmd
, the string$0
will get interpolated to the current script name or node command for the present script similar to how$0
works in bash or perl. Examples will be printed out as part of the help message.
method exit
exit: (code: number, err: Error) => void;
Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by
.exitProcess().
method exitProcess
exitProcess: (enabled: boolean) => Argv<T>;
By default, yargs exits the process when the user passes a help flag, the user uses the
.version
functionality, validation fails, or the command handler fails. Calling.exitProcess(false)
disables this behavior, enabling further actions after yargs have been validated.
method fail
fail: ( func: boolean | ((msg: string, err: Error, yargs: Argv<T>) => any)) => Argv<T>;
Method to execute when a failure occurs, rather than printing the failure message.
Parameter func
Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred.
method getCompletion
getCompletion: { ( args: readonly string[], done: (err: Error | null, completions: readonly string[]) => void ): Argv<T>; (args: readonly string[], done?: never): Promise<readonly string[]>;};
Allows to programmatically get completion choices for any line.
Parameter args
An array of the words in the command line to complete.
Parameter done
The callback to be called with the resulting completions.
method getHelp
getHelp: () => Promise<string>;
Returns a promise which resolves to a string containing the help text.
method global
global: (key: string | readonly string[]) => Argv<T>;
Indicate that an option (or group of options) should not be reset when a command is executed
Options default to being global.
method group
group: (key: string | readonly string[], groupName: string) => Argv<T>;
Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions
method help
help: { (): Argv<T>; (enableExplicit: boolean): Argv<T>; (option: string, enableExplicit: boolean): Argv<T>; (option: string, description?: string, enableExplicit?: boolean): Argv<T>;};
Configure an (e.g.
--help
) and implicit command that displays the usage string and exits the process. By default yargs enables help on the--help
option.Note that any multi-char aliases (e.g.
help
) used for the help option will also be used for the implicit command. If there are no multi-char aliases (e.g.h
), then all single-char aliases will be used for the command.If invoked without parameters,
.help()
will use--help
as the option and help as the implicit command to trigger help output.Parameter description
Customizes the description of the help option in the usage string.
Parameter enableExplicit
If
false
is provided, it will disable --help.
method hide
hide: (key: string) => Argv<T>;
Hides a key from the generated usage information. Unless a
--show-hidden
option is also passed with--help
(seeshowHidden()
).
method implies
implies: { (key: string, value: string | readonly string[]): Argv<T>; (implies: { [key: string]: string | readonly string[] }): Argv<T>;};
Given the key
x
is set, it is required that the keyy
is set. ycan either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with
x`.Optionally
.implies()
can accept an object specifying multiple implications.
method locale
locale: { (): string; (loc: string): Argv<T> };
Return the locale that yargs is currently using.
By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language.
Override the auto-detected locale from the user's operating system with a static locale. Note that the OS locale can be modified by setting/exporting the
LC_ALL
environment variable.
method middleware
middleware: ( callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>, applyBeforeValidation?: boolean) => Argv<T>;
Define global middleware functions to be called first, in list order, for all cli command.
Parameter callbacks
Can be a function or a list of functions. Each callback gets passed a reference to argv.
Parameter applyBeforeValidation
Set to
true
to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing.
method nargs
nargs: { (key: string, count: number): Argv<T>; (nargs: { [key: string]: number }): Argv<T>;};
The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity.
Optionally
.nargs()
can take an object ofkey
/narg
pairs.
method normalize
normalize: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: ToString<T[key]> } >; <K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string }>;};
The key provided represents a path and should have
path.normalize()
applied.
method number
number: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: ToNumber<T[key]> } >; <K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number }>;};
Tell the parser to always interpret key as a number.
If
key
is an array, all elements will be parsed as numbers.If the option is given on the command line without a value,
argv
will be populated withundefined
.If the value given on the command line cannot be parsed as a number,
argv
will be populated withNaN
.Note that decimals, hexadecimals, and scientific notation are all accepted.
method onFinishCommand
onFinishCommand: (func: (result: any) => void) => Argv<T>;
Method to execute when a command finishes successfully.
Parameter func
Is called with the successful result of the command that finished.
method option
option: { <K extends keyof T, O extends Options>(key: K, options: O): Argv< Omit<T, K> & { [key in K]: InferredOptionType<O> } & Alias<O> >; <K extends string, O extends Options>(key: K, options: O): Argv< T & { [key in K]: InferredOptionType<O> } & Alias<O> >; <O extends { [key: string]: Options }>(options: O): Argv< Omit<T, keyof O> & InferredOptionTypes<O> & Alias<O> >;};
This method can be used to make yargs aware of options that could exist. You can also pass an opt object which can hold further customization, like
.alias()
,.demandOption()
etc. for that option.
method options
options: { <K extends keyof T, O extends Options>(key: K, options: O): Argv< Omit<T, K> & { [key in K]: InferredOptionType<O> } >; <K extends string, O extends Options>(key: K, options: O): Argv< T & { [key in K]: InferredOptionType<O> } >; <O extends { [key: string]: Options }>(options: O): Argv< Omit<T, keyof O> & InferredOptionTypes<O> >;};
This method can be used to make yargs aware of options that could exist. You can also pass an opt object which can hold further customization, like
.alias()
,.demandOption()
etc. for that option.
method parse
parse: { (): | { [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; } | Promise<{ [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }>; ( arg: string | readonly string[], context?: object, parseCallback?: ParseCallback<T> ): | { [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; } | Promise<{ [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }>;};
Parse
args
instead ofprocess.argv
. Returns theargv
object.args
may either be a pre-processed argv array, or a raw argument string.Note: Providing a callback to parse() disables the
exitProcess
setting until after the callback is invoked.Parameter context
Provides a useful mechanism for passing state information to commands
method parseAsync
parseAsync: { (): Promise<{ [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }>; ( arg: string | readonly string[], context?: object, parseCallback?: ParseCallback<T> ): Promise<{ [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }>;};
method parserConfiguration
parserConfiguration: ( configuration: Partial<ParserConfigurationOptions>) => Argv<T>;
Allows to configure advanced yargs features.
method parseSync
parseSync: { (): { [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; }; ( arg: string | readonly string[], context?: object, parseCallback?: ParseCallback<T> ): { [key in keyof Arguments<T> as | key | CamelCaseKey<key>]: Arguments<T>[key]; };};
method pkgConf
pkgConf: (key: string | readonly string[], cwd?: string) => Argv<T>;
Similar to
config()
, indicates that yargs should interpret the object from the specified key in package.json as a configuration object.Parameter cwd
If provided, the package.json will be read from this location
method positional
positional: { <K extends keyof T, O extends PositionalOptions>(key: K, opt: O): Argv< Omit<T, K> & { [key in K]: InferredOptionType<O> } >; <K extends string, O extends PositionalOptions>(key: K, opt: O): Argv< T & { [key in K]: InferredOptionType<O> } >;};
Allows you to configure a command's positional arguments with an API similar to
.option()
..positional()
should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error.
method recommendCommands
recommendCommands: () => Argv<T>;
Should yargs provide suggestions regarding similar commands if no matching command is found?
method require
require: { <K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv< Defined<T, K> >; (key: string, msg: string): Argv<T>; (key: string, required: boolean): Argv<T>; (keys: readonly number[], msg: string): Argv<T>; (keys: readonly number[], required: boolean): Argv<T>; (positionals: number, required: boolean): Argv<T>; (positionals: number, msg: string): Argv<T>;};
Deprecated
since version 6.6.0 Use '.demandCommand()' or '.demandOption()' instead
method required
required: { <K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv< Defined<T, K> >; (key: string, msg: string): Argv<T>; (key: string, required: boolean): Argv<T>; (keys: readonly number[], msg: string): Argv<T>; (keys: readonly number[], required: boolean): Argv<T>; (positionals: number, required: boolean): Argv<T>; (positionals: number, msg: string): Argv<T>;};
Deprecated
since version 6.6.0 Use '.demandCommand()' or '.demandOption()' instead
method requiresArg
requiresArg: (key: string | readonly string[]) => Argv<T>;
method scriptName
scriptName: ($0: string) => Argv<T>;
Set the name of your script ($0). Default is the base filename executed by node (
process.argv[1]
)
method showCompletionScript
showCompletionScript: () => Argv<T>;
Generate a bash completion script. Users of your application can install this script in their
.bashrc
, and yargs will provide completion shortcuts for commands and options.
method showHelp
showHelp: { (consoleLevel?: string): Argv<T>; (printCallback: (s: string) => void): Argv<T>;};
Print the usage data using the console function consoleLevel for printing.
Parameter consoleLevel
Provide the usage data as a string.
Parameter printCallback
a function with a single argument.
method showHelpOnFail
showHelpOnFail: (enable: boolean, message?: string) => Argv<T>;
By default, yargs outputs a usage string if any error is detected. Use the
.showHelpOnFail()
method to customize this behavior.Parameter enable
If
false
, the usage string is not output.Parameter message
Message that is output after the error message.
method showHidden
showHidden: { (option?: string | boolean): Argv<T>; (option: string, description?: string): Argv<T>;};
Configure the
--show-hidden
option that displays the hidden keys (seehide()
).Parameter option
If
boolean
, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument isfalse
. Ifstring
it changes the key name ("--show-hidden").Parameter description
Changes the default description ("Show hidden options")
method showVersion
showVersion: (level?: 'error' | 'log' | ((message: string) => void)) => Argv<T>;
Print the version data using the console function consoleLevel or the specified function.
Parameter level
method skipValidation
skipValidation: (key: string | readonly string[]) => Argv<T>;
Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped.
method strict
strict: { (): Argv<T>; (enabled: boolean): Argv<T> };
Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error.
Unrecognized commands will also be reported as errors.
method strictCommands
strictCommands: { (): Argv<T>; (enabled: boolean): Argv<T> };
Similar to .strict(), except that it only applies to unrecognized commands. A user can still provide arbitrary options, but unknown positional commands will raise an error.
method strictOptions
strictOptions: { (): Argv<T>; (enabled: boolean): Argv<T> };
Similar to
.strict()
, except that it only applies to unrecognized options. A user can still provide arbitrary positional options, but unknown options will raise an error.
method string
string: { <K extends keyof T>(key: K | readonly K[]): Argv< Omit<T, K> & { [key in K]: ToString<T[key]> } >; <K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string }>;};
Tell the parser logic not to interpret
key
as a number or boolean. This can be useful if you need to preserve leading zeros in an input.If
key
is an array, interpret all the elements as strings..string('_')
will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers.
method terminalWidth
terminalWidth: () => number;
method updateLocale
updateLocale: (obj: { [key: string]: string }) => Argv<T>;
method updateStrings
updateStrings: (obj: { [key: string]: string }) => Argv<T>;
Override the default strings used by yargs with the key/value pairs provided in obj
If you explicitly specify a locale(), you should do so before calling
updateStrings()
.
method usage
usage: { (message: string): Argv<T>; <U>( command: string | readonly string[], description: string, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void> ): Argv<T>; <U>( command: string | readonly string[], showInHelp: boolean, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: ArgumentsCamelCase<U>) => void | Promise<void> ): Argv<T>; <O extends { [key: string]: Options }>( command: string | readonly string[], description: string, builder?: O, handler?: ( args: ArgumentsCamelCase<InferredOptionTypes<O>> ) => void | Promise<void> ): Argv<T>; <O extends { [key: string]: Options }>( command: string | readonly string[], showInHelp: boolean, builder?: O, handler?: ( args: ArgumentsCamelCase<InferredOptionTypes<O>> ) => void | Promise<void> ): Argv<T>;};
Set a usage message to show which commands to use. Inside
message
, the string$0
will get interpolated to the current script name or node command for the present script similar to how$0
works in bash or perl.If the optional
description
/builder
/handler
are provided,.usage()
acts an an alias for.command()
. This allows you to use.usage()
to configure the default command that will be run as an entry-point to your application and allows you to provide configuration for the positional arguments accepted by your program:
method version
version: { (): Argv<T>; (version: string): Argv<T>; (enable: boolean): Argv<T>; (optionKey: string, version: string): Argv<T>; (optionKey: string, description: string, version: string): Argv<T>;};
Add an option (e.g.
--version
) that displays the version number (given by the version parameter) and exits the process. By default yargs enables version for the--version
option.If no arguments are passed to version (
.version()
), yargs will parse the package.json of your module and use its version value.If the boolean argument
false
is provided, it will disable--version
.
method wrap
wrap: (columns: number | null) => Argv<T>;
Format usage output to wrap at columns many columns.
By default wrap will be set to
Math.min(80, windowWidth)
. Use.wrap(null)
to specify no column limit (no right-align). Use.wrap(yargs.terminalWidth())
to maximize the width of yargs' usage instructions.
call signature
(args?: readonly string[] | string, cwd?: string): Argv<T>;
interface CommandModule
interface CommandModule<T = {}, U = {}> {}
property aliases
aliases?: readonly string[] | string | undefined;
array of strings (or a single string) representing aliases of
exports.command
, positional args defined in an alias are ignored
property builder
builder?: CommandBuilder<T, U> | undefined;
object declaring the options the command accepts, or a function accepting and returning a yargs instance
property command
command?: readonly string[] | string | undefined;
string (or array of strings) that executes this command when given on the command line, first string may contain positional args
property deprecated
deprecated?: boolean | string | undefined;
boolean (or string) to show deprecation notice
property describe
describe?: string | false | undefined;
string used as the description for the command in help text, use
false
for a hidden command
property handler
handler: (args: ArgumentsCamelCase<U>) => void | Promise<void>;
a function which will be passed the parsed argv.
interface Options
interface Options {}
property alias
alias?: string | readonly string[] | undefined;
string or array of strings, alias(es) for the canonical option key, see
alias()
property array
array?: boolean | undefined;
boolean, interpret option as an array, see
array()
property boolean
boolean?: boolean | undefined;
boolean, interpret option as a boolean flag, see
boolean()
property choices
choices?: Choices | undefined;
value or array of values, limit valid option arguments to a predefined set, see
choices()
property coerce
coerce?: ((arg: any) => any) | undefined;
function, coerce or transform parsed command line values into another value, see
coerce()
property config
config?: boolean | undefined;
boolean, interpret option as a path to a JSON config file, see
config()
property configParser
configParser?: ((configPath: string) => object) | undefined;
function, provide a custom config parsing function, see
config()
property conflicts
conflicts?: | string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
string or object, require certain keys not to be set, see
conflicts()
property count
count?: boolean | undefined;
boolean, interpret option as a count of boolean flags, see
count()
property default
default?: any;
value, set a default value for the option, see
default()
property defaultDescription
defaultDescription?: string | undefined;
string, use this description for the default value in help content, see
default()
property demand
demand?: boolean | string | undefined;
Deprecated
since version 6.6.0 Use 'demandOption' instead
property demandOption
demandOption?: boolean | string | undefined;
boolean or string, demand the option be given, with optional error message, see
demandOption()
property deprecate
deprecate?: boolean | string | undefined;
boolean or string, mark the argument as deprecated, see
deprecateOption()
property deprecated
deprecated?: boolean | string | undefined;
boolean or string, mark the argument as deprecated, see
deprecateOption()
property desc
desc?: string | undefined;
string, the option description for help content, see
describe()
property describe
describe?: string | undefined;
string, the option description for help content, see
describe()
property description
description?: string | undefined;
string, the option description for help content, see
describe()
property global
global?: boolean | undefined;
boolean, indicate that this key should not be reset when a command is invoked, see
global()
property group
group?: string | undefined;
string, when displaying usage instructions place the option under an alternative group heading, see
group()
property hidden
hidden?: boolean | undefined;
don't display option in help output.
property implies
implies?: | string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
string or object, require certain keys to be set, see
implies()
property nargs
nargs?: number | undefined;
number, specify how many arguments should be consumed for the option, see
nargs()
property normalize
normalize?: boolean | undefined;
boolean, apply path.normalize() to the option, see
normalize()
property number
number?: boolean | undefined;
boolean, interpret option as a number,
number()
property require
require?: boolean | string | undefined;
Deprecated
since version 6.6.0 Use 'demandOption' instead
property required
required?: boolean | string | undefined;
Deprecated
since version 6.6.0 Use 'demandOption' instead
property requiresArg
requiresArg?: boolean | undefined;
boolean, require the option be specified with a value, see
requiresArg()
property skipValidation
skipValidation?: boolean | undefined;
boolean, skips validation if the option is present, see
skipValidation()
property string
string?: boolean | undefined;
boolean, interpret option as a string, see
string()
property type
type?: 'array' | 'count' | PositionalOptionsType | undefined;
interface PositionalOptions
interface PositionalOptions {}
property alias
alias?: string | readonly string[] | undefined;
string or array of strings, see
alias()
property array
array?: boolean | undefined;
boolean, interpret option as an array, see
array()
property choices
choices?: Choices | undefined;
value or array of values, limit valid option arguments to a predefined set, see
choices()
property coerce
coerce?: ((arg: any) => any) | undefined;
function, coerce or transform parsed command line values into another value, see
coerce()
property conflicts
conflicts?: | string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
string or object, require certain keys not to be set, see
conflicts()
property default
default?: any;
value, set a default value for the option, see
default()
property demandOption
demandOption?: boolean | string | undefined;
boolean or string, demand the option be given, with optional error message, see
demandOption()
property desc
desc?: string | undefined;
string, the option description for help content, see
describe()
property describe
describe?: string | undefined;
string, the option description for help content, see
describe()
property description
description?: string | undefined;
string, the option description for help content, see
describe()
property implies
implies?: | string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
string or object, require certain keys to be set, see
implies()
property normalize
normalize?: boolean | undefined;
boolean, apply path.normalize() to the option, see normalize()
property type
type?: PositionalOptionsType | undefined;
interface RequireDirectoryOptions
interface RequireDirectoryOptions {}
property exclude
exclude?: RegExp | ((pathToFile: string) => boolean) | undefined;
Blacklist certain modules.
property extensions
extensions?: readonly string[] | undefined;
The types of files to look for when requiring command modules.
property include
include?: RegExp | ((pathToFile: string) => boolean) | undefined;
Whitelist certain modules
property recurse
recurse?: boolean | undefined;
Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list.
property visit
visit?: | ((commandObject: any, pathToFile?: string, filename?: string) => any) | undefined;
A synchronous function called for each command module encountered. Accepts
commandObject
,pathToFile
, andfilename
as arguments. ReturnscommandObject
to include the command; any falsy value to exclude/skip it.
Type Aliases
type Alias
type Alias<O extends Options | PositionalOptions> = O extends { alias: infer T } ? T extends Exclude<string, T> ? { [key in T]: InferredOptionType<O> } : {} : {};
type Arguments
type Arguments<T = {}> = T & { /** Non-option arguments */ _: Array<string | number>; /** The script name or node command */ $0: string; /** All remaining options */ [argName: string]: unknown;};
type ArgumentsCamelCase
type ArgumentsCamelCase<T = {}> = { [key in keyof T as key | CamelCaseKey<key>]: T[key];} & { /** Non-option arguments */ _: Array<string | number>; /** The script name or node command */ $0: string; /** All remaining options */ [argName: string]: unknown;};
Arguments type, with camelcased keys
type AsyncCompletionFunction
type AsyncCompletionFunction = ( current: string, argv: any, done: (completion: readonly string[]) => void) => void;
type BuilderArguments
type BuilderArguments< T extends (...args: any) => R, R = ReturnType<T>> = R extends Argv<infer X> ? ArgumentsCamelCase<X> : {} | R extends PromiseLike<Argv<infer X>> ? ArgumentsCamelCase<X> : {};
type BuilderCallback
type BuilderCallback<T, R> = | ((args: Argv<T>) => PromiseLike<Argv<R>>) | ((args: Argv<T>) => Argv<R>) | ((args: Argv<T>) => void);
type CamelCase
type CamelCase<S extends string> = string extends S ? string : S extends `${infer T}-${infer U}` ? `${T}${PascalCase<U>}` : S;
Convert literal string types like 'foo-bar' to 'fooBar'
type CamelCaseKey
type CamelCaseKey<K extends PropertyKey> = K extends string ? Exclude<CamelCase<K>, ''> : K;
Convert literal string types like 'foo-bar' to 'fooBar', allowing all
PropertyKey
types
type Choices
type Choices = ReadonlyArray<string | number | true | undefined>;
type CommandBuilder
type CommandBuilder<T = {}, U = {}> = | { [key: string]: Options } | ((args: Argv<T>) => Argv<U>) | ((args: Argv<T>) => PromiseLike<Argv<U>>);
type CompletionCallback
type CompletionCallback = ( err: Error | null, completions: string[] | undefined) => void;
type Defined
type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined>;};
Remove undefined as a possible value for keys K in T
type FallbackCompletionFunction
type FallbackCompletionFunction = ( current: string, argv: any, completionFilter: (onCompleted?: CompletionCallback) => any, done: (completions: string[]) => any) => void;
type InferredOptionType
type InferredOptionType<O extends Options | PositionalOptions> = // Handle special cases first O extends { coerce: (arg: any) => infer T } ? IsRequiredOrHasDefault<O> extends true ? T : T | undefined : O extends | { type: 'count'; default: infer D } | { count: true; default: infer D } ? number | Exclude<D, undefined> : O extends { type: 'count' } | { count: true } ? number : // Try to infer type with InferredOptionTypePrimitive IsUnknown<InferredOptionTypePrimitive<O>> extends false ? InferredOptionTypePrimitive<O> : // Use the type of `default` as the last resort O extends { default: infer D } ? Exclude<D, undefined> : unknown;
type InferredOptionTypeInner
type InferredOptionTypeInner<O extends Options | PositionalOptions> = O extends { type: 'array'; choices: ReadonlyArray<infer C>;} ? C[] : O extends { type: 'array'; string: true } ? string[] : O extends { type: 'array'; number: true } ? number[] : O extends { type: 'array'; normalize: true } ? string[] : O extends { array: true; choices: ReadonlyArray<infer C> } ? C[] : O extends { array: true; type: 'string' } ? string[] : O extends { array: true; type: 'number' } ? number[] : O extends { array: true; string: true } ? string[] : O extends { array: true; number: true } ? number[] : O extends { array: true; normalize: true } ? string[] : O extends { choices: ReadonlyArray<infer C> } ? C : O extends { type: 'array' } ? Array<string | number> : O extends { type: 'boolean' } ? boolean : O extends { type: 'number' } ? number : O extends { type: 'string' } ? string : O extends { array: true } ? Array<string | number> : O extends { boolean: true } ? boolean : O extends { number: true } ? number : O extends { string: true } ? string : O extends { normalize: true } ? string : unknown;
type InferredOptionTypePrimitive
type InferredOptionTypePrimitive<O extends Options | PositionalOptions> = O extends { default: infer D;} ? IsRequiredOrHasDefault<O> extends true ? InferredOptionTypeInner<O> | Exclude<D, undefined> : InferredOptionTypeInner<O> | D : IsRequiredOrHasDefault<O> extends true ? InferredOptionTypeInner<O> : InferredOptionTypeInner<O> | undefined;
type InferredOptionTypes
type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]>;};
type IsAny
type IsAny<T> = 0 extends 1 & T ? true : false;
type IsRequiredOrHasDefault
type IsRequiredOrHasDefault<O extends Options | PositionalOptions> = O extends | { required: string | true } | { require: string | true } | { demand: string | true } | { demandOption: string | true } | { default: {} } ? true : false;
type IsUnknown
type IsUnknown<T> = IsAny<T> extends true ? false : unknown extends T ? true : false;
type MiddlewareFunction
type MiddlewareFunction<T = {}> = ( args: ArgumentsCamelCase<T>) => void | Promise<void>;
type Omit
type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] };
Remove keys K in T
type ParseCallback
type ParseCallback<T = {}> = ( err: Error | undefined, argv: ArgumentsCamelCase<T>, output: string) => void | Promise<void>;
type ParserConfigurationOptions
type ParserConfigurationOptions = Configuration & { /** Sort commands alphabetically. Default is `false` */ 'sort-commands': boolean;};
type PascalCase
type PascalCase<S extends string> = string extends S ? string : S extends `${infer T}-${infer U}` ? `${Capitalize<T>}${PascalCase<U>}` : Capitalize<S>;
Convert literal string types like 'foo-bar' to 'FooBar'
type PositionalOptionsType
type PositionalOptionsType = 'boolean' | 'number' | 'string';
type PromiseCompletionFunction
type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>;
type SyncCompletionFunction
type SyncCompletionFunction = (current: string, argv: any) => string[];
type ToArray
type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>;
Convert T to T[] and T | undefined to T[] | undefined
type ToNumber
type ToNumber<T> = | (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;
Gives number[] if T is an array type, otherwise number. Preserves | undefined.
type ToString
type ToString<T> = | (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>;
Gives string[] if T is an array type, otherwise string. Preserves | undefined.
Package Files (1)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/yargs
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/yargs)
- HTML<a href="https://www.jsdocs.io/package/@types/yargs"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5830 ms. - Missing or incorrect documentation? Open an issue for this package.