Skip to content

Commit

Permalink
Allow generics to type arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
adhamu committed Nov 24, 2022
1 parent 2a9ac06 commit 163d32b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { arge } from 'arge'

Then:

```typescript
```javascript
const args = arge(process.argv)
```

Expand All @@ -43,6 +43,33 @@ node app.js --dry-run --mode=development --test=false --retries=100
}
```

## Typescript

For type safety, `arge` will accept a generic for typing the resulting object.

### Example

```typescript
const { foo, bar } = arge(process.argv)
```

In the above scenario, `foo` and `bar` will report the following:

> Property 'foo' does not exist on type 'unknown'
> Property 'bar' does not exist on type 'unknown'
To address this, we can apply a generic:

```typescript
interface Args {
foo: string
bar: number
}

const { foo, bar } = arge<Args>(process.argv)
```

## API

### arge(flags, options?)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "arge",
"version": "1.1.4",
"version": "1.2.0",
"description": "A simple utility to parse command line arguments and flags",
"keywords": [
"argv",
Expand Down
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ const parse = (value: string): Value => {
return value
}

export const arge = (
export const arge = <T>(
args: string[],
options: Options = {
isArgv: true,
camelCaseKeys: true,
}
): Record<string, Value> =>
): T =>
(options.isArgv !== false
? args.filter((_, index) => index > 1)
: args
Expand All @@ -53,4 +53,4 @@ export const arge = (
...acc,
[`${key.trim()}`]: parse(v.trim()),
}
}, {})
}, {} as T)

0 comments on commit 163d32b

Please sign in to comment.