This rule raises an issue when a generic Error is thrown immediately after an if-statement that performs type checking operations.

Why is this an issue?

JavaScript provides specific error types for different kinds of problems. When you’re checking types and throwing errors based on those checks, using a generic Error is less precise than using TypeError.

TypeError is the standard JavaScript error type specifically designed for situations where a value is not of the expected type. Using the correct error type makes your code more semantically accurate and helps other developers (and tools) understand what went wrong.

When you use TypeError instead of Error for type-related issues, you provide better context about the nature of the problem. This makes debugging easier and follows JavaScript best practices for error handling.

The rule recognizes common type checking patterns including:

What is the potential impact?

Using generic Error instead of TypeError for type-related issues reduces code clarity and makes debugging more difficult. It also goes against JavaScript conventions and best practices for error handling.

How to fix?

Replace Error with TypeError when throwing after type checking conditions. The error message can remain the same.

Non-compliant code example

if (Array.isArray(foo) === false) {
	throw new Error('Array expected'); // Noncompliant
}

Compliant code example

if (Array.isArray(foo) === false) {
	throw new TypeError('Array expected');
}

Documentation

Standards