unicorn/no-instanceof-builtins
Disallow instanceof with built-in constructors such as Array, String, and Function
has suggestions
instanceof gives the wrong answer for built-ins in two ways. First, a primitive is never an instance, so "text" instanceof String is false. Second, every iframe and every node:vm context has its own built-ins, so an array or a function from another one isn't an instance of your Array or Function.
By default, the rule reports instanceof with Array, Function, String, Number, Boolean, BigInt, and Symbol. --fix-suggestions rewrites these to Array.isArray(value) or a typeof check.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-instanceof-builtins" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"unicorn/no-instanceof-builtins" = ["error", {
strategy = "loose",
useErrorIsError = false,
include = [], # list of strings
exclude = [],
}]Examples#
example.js2 problems
function describe(value) {
if (value instanceof StringDo not use instanceof with built-in constructors) return "text";
if (value instanceof FunctionDo not use instanceof with built-in constructors) return "callback";
}example.jsNo problems
function describe(value) {
if (typeof value === "string") return "text";
if (typeof value === "function") return "callback";
if (value instanceof Map) return "map";
}Options#
| Option | Default | What it does |
|---|---|---|
strategy | "loose" | "strict" also reports the error classes, Map, Set, Date, RegExp, Promise, Object, the typed arrays, and other built-in classes. |
useErrorIsError | false | Also report instanceof Error, and suggest Error.isError(value). |
include | [] | More constructor names to report. |
exclude | [] | Constructor names to never report. |
example.jswith
{ "strategy": "strict" }2 problemsif (value instanceof DateDo not use instanceof with built-in constructors || value instanceof TypeErrorDo not use instanceof with built-in constructors) {
log(value);
}example.jswith
{ "useErrorIsError": true }1 problemif (reason instanceof ErrorDo not use instanceof with built-in constructors) {
log(reason.message);
}example.jswith
{ "include": ["HTMLElement"] }1 problemif (target instanceof HTMLElementDo not use instanceof with built-in constructors) {
target.focus();
}