is-required
v1.0.5
Published
Required parameters for functions
Downloads
28
Maintainers
Readme
Required parameters
Throws an error when a given parameter is not provided to a function.
In ECMAScript 6, the default argument expression gets evaluated at call time
when a parameter is missing or undefined. You can use required()
as a default value
to make that parameter to be provided forcibly, throwing an error.
It is better to catch and identify such an error as early as possible rather than get something like
TypeError: Cannot read property 'body' of undefined
.
You can also use isRequired()
during destructuring assignment (as default value). See the examples below.
Installation
npm i --save is-required
Usage examples
Parameter val
is required:
const isRequired = require('is-required');
function foo (val = isRequired('val')) {
return val;
}
foo();
Throws Error:
Error: Undefined or missing parameter "val" in function "foo"
You can omit the name:
const required = require('is-required');
function bar (myParam = required()) {
return myParam;
}
bar();
//Error: Undefined or missing parameter in function "foo"
Destructuring:
const {
method = 'GET',
url = isRequired('url'), // <--
multipart: {
data: multipartData = {}
}
} = params || {};