Skip to content

Commit

Permalink
docs: typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolay-borzov authored and bcoe committed Jul 29, 2019
1 parent e3981fd commit 8877bce
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
[![Slack][slack-image]][slack-url]

## Description :
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.

It gives you:

Expand Down Expand Up @@ -87,6 +87,16 @@ require('yargs') // eslint-disable-line

Run the example above with `--help` to see the help for the application.

## TypeScript

yargs has type definitions at `@types/yargs`

```
npm i -D @types/yargs
```

See usage examples in [docs](/docs/typescript.md)

## Community :

Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com).
Expand Down
59 changes: 59 additions & 0 deletions docs/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# TypeScript usage examples

Options type inference work pretty well

```typescript
#!/usr/bin/env node
import yargs from 'yargs';

const argv = yargs.options({
a: { type: 'boolean', default: false },
b: { type: 'string', demandOption: true },
c: { type: 'number', alias: 'chill' },
d: { type: 'array' },
e: { type: 'count' },
f: { choices: ['1', '2', '3'] }
}).argv;

```
`argv` will get type
```typescript
{
[x: string]: unknown;
a: boolean;
b: string;
c: number | undefined;
d: (string | number)[] | undefined;
e: number;
f: string | undefined;
_: string[];
$0: string;
}
```

You might want to declare an interface for arguments object
```typescript
interface Arguments {
[x: string]: unknown;
a: boolean;
b: string;
c: number | undefined;
d: (string | number)[] | undefined;
e: number;
f: string | undefined;
}
```

To improve `choices` option typing you can specify type for choices

```typescript
type Difficulty = 'normal' | 'nightmare' | 'hell';
const difficulties: ReadonlyArray<Difficulty> = ['normal', 'nightmare', 'hell'];

const argv = yargs.option('difficulty', {
choices: difficulties,
demandOption: true
}).argv;
```

`argv` will get type `'normal' | 'nightmare' | 'hell'`

0 comments on commit 8877bce

Please sign in to comment.