UNPKG

2.67 kBMarkdownView Raw
1# assert-options
2
3Smart `options` handling, with one line of code:
4
5* throw detailed error on invalid options
6* set default values for missing options
7
8Strongly-typed, built with TypeScript 4.x `strict` mode, for JavaScript clients.
9
10[![Build Status](https://travis-ci.org/vitaly-t/assert-options.svg?branch=master)](https://travis-ci.org/vitaly-t/assert-options)
11[![Coverage Status](https://coveralls.io/repos/vitaly-t/assert-options/badge.svg?branch=master)](https://coveralls.io/r/vitaly-t/assert-options?branch=master)
12
13## Rationale
14
15* Passing in invalid or misspelled option names is one of the most common errors in JavaScript.
16* Assigning defaults is the most common operation for methods that take options.
17
18This module automates proper options handling - parsing and setting defaults where needed.
19
20Although this library is implemented in TypeScript, its objective is mainly to help JavaScript clients,
21because TypeScript itself can handle invalid options and defaults natively.
22
23## Installation
24
25```
26$ npm i assert-options
27```
28
29## Usage
30
31```js
32const { assertOptions } = require('assert-options');
33
34function functionWithOptions(options) {
35 options = assertOptions(options, {first: 123, second: null});
36
37 // options is a safe object here, with all missing defaults set.
38}
39```
40
41When default values are not needed, you can just use an array of strings:
42
43```js
44function functionWithOptions(options) {
45 options = assertOptions(options, ['first', 'second']);
46
47 // the result is exactly the same as using the following:
48 // options = assertOptions(options, {first: undefined, second: undefined});
49
50 // options is a safe object here, without defaults.
51}
52```
53
54## API
55
56### `assertOptions(options, defaults) => {}`
57
58* When `options` is `null`/`undefined`, new `{}` is returned, applying `defaults` as specified.
59
60* When `options` contains an unknown property, [Error] `Option "name" is not recognized.` is thrown.
61
62* When a property in `options` is missing or `undefined`, its value is set from the `defaults`,
63provided it is available and its value is not `undefined`.
64
65* When `options` is not `null`/`undefined`, it must be of type `object`, or else [TypeError] is thrown:
66`Invalid "options" parameter: value`.
67
68* Parameter `defaults` is required, as a non-`null` object or an array of strings, or else [TypeError]
69is thrown: `Invalid "defaults" parameter: value`.
70
71[Error]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
72[TypeError]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError