is-required

1.0.5 • Public • Published

Required parameters

Throws an error when a given parameter is not provided to a function.

NPM Version NPM Downloads GitHub issues Telegram

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 || {};

Dependencies (0)

    Dev Dependencies (1)

    Package Sidebar

    Install

    npm i is-required

    Weekly Downloads

    4

    Version

    1.0.5

    License

    MIT

    Last publish

    Collaborators

    • doasync