Skip to content

A babel plugin that prevents coercion and silent failure in JavaScript

License

Notifications You must be signed in to change notification settings

amilajack/babel-plugin-fail-explicit

Repository files navigation

babel-plugin-fail-explicit

Build Status NPM version Dependency Status npm

A babel plugin that prevents coercion and silent failure in JavaScript

demo

Roadmap

  • Fail on unsafe coercion
  • Fail on unsafe property access
  • Do not fail inside conditional expressions or default statements (||), on by default
  • Allow unsafe access in if statement by default
  • Allow for configuration of strictness

Installation

npm install --save-dev babel-plugin-fail-explicit

Setup

// .babelrc
{
  "plugins": [
    "fail-explicit"
  ]
}

Demo:

To experiment with babel-plugin-fail-explicit, see this demo repo

Examples

// ------------------------------------------------
// Coercion safeguard
// ------------------------------------------------
[] + {}
// TypeError: 'Unexpected coercion of type "Array" and
// type "Object" using "+" operator'

NaN + undefined
// TypeError: Unexpected coercion of type "NaN" and type
// "undefined" using "+" operator

1 + 'some'
// '1some'


// ------------------------------------------------
// Safe Comparison
// ------------------------------------------------
new String('12') > 12
// TypeError: Unexpected comparison of type "String" and type
// "number" using ">" operator

null > undefined
// TypeError: Unexpected comparison of type "null" and type
// "undefined" using ">" operator


// ------------------------------------------------
// Usage for better undefined propagation errors
// ------------------------------------------------
const obj = {
  foo: {
    bar: {}
  }
}

obj.foo.bar.baz;
// TypeError: Property "baz" does not exist in "Object.foo.bar"


// ------------------------------------------------
// Usage as out of bounds check
// ------------------------------------------------
const some = new Array(3)
some[10]
// TypeError: '"Array[10]" is out of bounds'

const bar = []
some[100]
// TypeError: '"Array[100]" is out of bounds'

// TypeError: '"woo[1]" is out of bounds'
const obj = {
  woo: ['']
}

obj.woo[1]
// TypeError: '"woo[1]" is out of bounds'