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 String) return "text";
  if (value instanceof Function) 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#

OptionDefaultWhat it does
strategy"loose""strict" also reports the error classes, Map, Set, Date, RegExp, Promise, Object, the typed arrays, and other built-in classes.
useErrorIsErrorfalseAlso 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 problems
if (value instanceof Date || value instanceof TypeError) {
  log(value);
}
example.jswith { "useErrorIsError": true }1 problem
if (reason instanceof Error) {
  log(reason.message);
}
example.jswith { "include": ["HTMLElement"] }1 problem
if (target instanceof HTMLElement) {
  target.focus();
}