Enforce throwing TypeError
in type checking conditions ​
💼 This rule is enabled in the ✅ recommended
config.
🔧 This rule is automatically fixable by the --fix
CLI option.
This rule enforces you to throw a TypeError
after a type checking if-statement, instead of a generic Error
.
It's aware of the most commonly used type checking operators and identifiers like typeof
, instanceof
, .isString()
, etc, borrowed from ES2017, Underscore, Lodash, and jQuery. For a complete list of the recognized identifiers, please take a look at the identifier-definition.
The rule investigates every throw-statement which throws a generic Error
. It will fail if the throw-statement is the only expression in the surrounding block and is preceeded by an if-statement whose condition consists of type-checks exclusively. You have to replace the Error
with a TypeError
.
Fail ​
if (Array.isArray(foo) === false) {
throw new Error('Array expected');
}
if (Number.isNaN(foo) === false && Number.isInteger(foo) === false) {
throw new Error('Integer expected');
}
if (isNaN(foo) === false) {
throw new Error('Number expected');
}
if (typeof foo !== 'function' &&
foo instanceof CookieMonster === false &&
foo instanceof Unicorn === false) {
throw new Error('Magic expected');
}
Pass ​
if (Array.isArray(foo) === false) {
throw new TypeError('Array expected');
}
if (Number.isNaN(foo) === false && Number.isInteger(foo) === false) {
throw new TypeError('Integer expected');
}
if (isNaN(foo) === false) {
throw new TypeError('Number expected');
}
if (typeof foo !== 'function' &&
foo instanceof CookieMonster === false &&
foo instanceof Unicorn === false) {
throw new TypeError('Magic expected');
}