Runtyper
Protect your App from type-coercion bugs
Runtyper is a Babel plugin for runtime type-checking in JavaScript.
You should enable it for non-production build and check console for type-coercion warnings.
As it works in runtime - no manual type-annotations needed in your codebase.
Tested in:
Contents
Example
Imagine you have comparison x === y
and in runtime values are x = 1
, y = "1"
.
When executed you will get false
. In many cases this result is unexpected: you just missed type conversion.
After applying Runtyper it will show warning when such situation happen:
or you can configure to throw errors:
How it works
Runtyper wraps all type-important operations into function.
When line is executed, function checks the argument types first and only then returns the result.
For example, before:
if (x === y) { ... }
After (simplified):
if (strictEqual(x, y)) { ... }
function strictEqual(a, b) {
if (typeof a !== typeof b) {
console.warn('Strict compare of different types: ' + typeof a + ' === ' + typeof b);
}
return a === b;
}
Installation
- Ensure you have Babel installed
- Install Runtyper from npm:
npm install babel-plugin-runtyper --save-dev
Usage
-
No changes to your existing codebase needed.
-
Add babel-plugin-runtyper
to Babel config:
-
in .babelrc
:
{
"plugins": ["babel-plugin-runtyper"]
}
To apply plugin only for development builds consider Babel's env option:
{
"env": {
"development": {
"plugins": ["babel-plugin-runtyper"]
}
}
}
-
in webpack config:
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
plugins: [
['babel-plugin-runtyper', {enabled: process.env.NODE_ENV !== 'production'}]
]
}
}
}
]
}
Please note to run webpack as NODE_ENV='production' webpack -p
(see #2537)
-
in package.json
scripts:
"scripts": {
"runtyper": "babel src --out-dir out --plugins=babel-plugin-runtyper --source-maps"
}
-
Enable source-maps to see original place of error:
Tip: checkout examples directory to see browser and Node.js demos
Configuration
To configure plugin pass it to Babel as array:
plugins: [
['babel-plugin-runtyper', options]
]
Options
Name | Default | Values | Description |
---|
enabled | true | true , false | Is plugin enabled |
warnLevel | "warn" | "info" , "warn" , "error" , "break" | How do you want to be notified |
implicitAddStringNumber | "deny" | "allow" , "deny" | Allow/deny (variable1) + (variable2) where (variable1), (variable1) are (string, number) |
implicitEqualNull | "deny" | "allow" , "deny" | Allow/deny (variable1) === (variable2) where (variable1) or (variable2) is null |
implicitEqualUndefined | "deny" | "allow" , "deny" | Allow/deny (variable1) === (variable2) where (variable1) or (variable2) is undefined |
explicitAddEmptyString | "deny" | "allow" , "deny" | Allow/deny (variable) + "" where (variable) is not string |
explicitEqualTrue | "deny" | "allow" , "deny" | Allow/deny (variable) === true where (variable) is not boolean |
explicitEqualFalse | "deny" | "allow" , "deny" | Allow/deny (variable) === false where (variable) is not boolean |
implicitEqualCustomTypes | "deny" | "allow" , "deny" | Allow/deny (variable1) === (variable2) where (variable1) instanceof MyClass1 and (variable2) instanceof MyClass2 |
excludeOperators | [] | ["equal", "numeric", "add", "relational"] | Excludes operators checking where equal excludes === , numeric excludes -, *, /, % , add excludes + and relational excludes >, >=, <, <= |
forbiddenNodeEnvs | ["production"] | Array<String> | Values of NODE_ENV where plugin shows warning if enabled |
Warning level description
info
- notification via console.info
without stacktracewarn
- notification via console.warn
with stacktraceerror
- notification via console.error
with stacktracebreak
- notification via throwing error and breaking execution
The softest configuration
By default configuration is very strict. You can start with the softest one:
{
enabled: true,
implicitAddStringNumber: "allow",
implicitEqualNull: "allow",
implicitEqualUndefined: "allow",
explicitAddEmptyString: "allow",
explicitEqualTrue: "allow",
explicitEqualFalse: "allow",
implicitEqualCustomTypes: "allow"
}
The result can be something like this:
Error: Strict equal of different types: -1 (number) === "" (string)
Error: Strict equal of different types: 2 (number) === "" (string)
Error: Strict equal of different types: 56.9364 (number) === "" (string)
Error: Strict equal of different types: -0.0869 (number) === "" (string)
Error: Numeric operation with non-numeric value: null / 60 (number)
Error: Numeric operation with non-numeric value: "2017-03-29T00:00:00... (Date) / 1000 (number)
Error: Numeric operation with non-numeric value: "2017-03-29T00:00:00... (Date) / 1000 (number)
...
Supported operators
-
Strict equality (===, !==
)
Protects you from:
1 === '1'
1 === [1]
1 === new Date()
...
-
Addition (+
)
Protects you from:
'1' + null
'1' + undefined
'1' + NaN
1 + NaN
1 + {}
...
-
Arithmetic (-, *, /, %
)
Protects you from:
1 - '1px'
1 - undefined
1 * null
1 * {}
...
-
Relational (>, >=, <, <=
)
Protects you from:
2 < '11'
1 < null
[1] < {}
2 < [11, null]
...
Ignore line
You can exclude line from checking by special comment:
if (x === y) {
...
}
Run on existing project
You can easily try Runtyper on existing project because no special code-annotations needed.
Just build your project with Runtyper enabled and perform some actions in the app. Then inspect the console.
You may see some warnings about type-mismatch operations:
Error: Strict equal of different types: -1 (number) === "" (string)
Error: Strict equal of different types: 2 (number) === "" (string)
Error: Strict equal of different types: 56.9364 (number) === "" (string)
Error: Strict equal of different types: -0.0869 (number) === "" (string)
Error: Numeric operation with non-numeric value: null / 60 (number)
Error: Numeric operation with non-numeric value: "2017-03-29T00:00:00... (Date) / 1000 (number)
Error: Numeric operation with non-numeric value: "2017-03-29T00:00:00... (Date) / 1000 (number)
...
Usage with Flow and TypeScript
Static code analysis also performs type checking.
You can use Runtyper together with Flow or TypeScript
to detect errors on both build and runtime stages.
Yet, static tools need extra efforts for:
- Writing type-annotations
- Integration with third-party libraries (as their API should be also annotated)
- Processing external events from user / server (many different formats)
- Training new members who is not familiar with typed JavaScript
To learn more about pros and cons of static types have a look on Eric Elliott's article You Might Not Need TypeScript (or Static Types).
Runtyper covers more cases due to it's runtime nature
Let's take an example from Flow's get started page:
function square(n) {
return n * n;
}
square("2");
But if square()
is used to handle user's input from text field - error will not be found:
function square(n) {
return n * n;
}
window.document.getElementById('username').addEventListener('change', function (event) {
square(event.target.value);
});
Runtyper allows to catch such cases in runtime:
Consider both approaches to make your applications more robust and reliable.
Articles
FAQ
-
Why I get error for template literals like ${name}${index}
?
Likely you are using babel-preset-es2015
that transforms template literals into concatenation +
.
And you get (string) + (number)
. You can fix it in several ways:
- set plugin option
implicitAddStringNumber: "allow"
- add explicit conversion:
${name}${String(index)}
- consider using babel-preset-env as
many browsers already have native support of template literals
-
Why explicit comparing like x === null
or x === undefined
are not warned?
When you explicitly write (variable) === null
you assume that variable can be null
.
-
Does it check non-strict equal ==
and !=
?
Nope. Non-strict comparison is a bad thing in most cases. Just quote Douglas Crockford from JavaScript, the Good Parts:
JavaScript has two sets of equality operators: ===
and !==
, and their evil twins ==
and !=
.
The good ones work the way you would expect. If the two operands are of the same type and have the same value,
then ===
produces true
and !==
produces false
. The evil twins do the right thing when the operands
are of the same type, but if they are of different types, they attempt to coerce the values.
The rules by which they do that are complicated and unmemorable.
These are some of the interesting cases:
'' == '0'
0 == ''
0 == '0'
false == 'false'
false == '0'
false == undefined
false == null
null == undefined
' \t\r\n ' == 0
The lack of transitivity is alarming. My advice is to never use ==
and !=
. Instead, always use ===
and !==
.
Explicit is always better when implicit, especially for readers of your code.
You can set ESLint eqeqeq rule and forget about ==
once and for all.
If you have other questions or ideas feel free to open new issue.
Related links
Contributors
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
License
MIT @ Vitaliy Potapov