π Disallow instanceof with built-in objects.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§π‘ This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.
Using instanceof to determine the type of an object has limitations.
Therefore, it is recommended to use a safer method, like Object.prototype.toString.call(foo) or the npm package @sindresorhus/is to determine the type of an object.
// β
foo instanceof String;
// β
typeof foo === 'string';// β
foo instanceof Number;
// β
typeof foo === 'number';// β
foo instanceof Boolean;
// β
typeof foo === 'boolean';// β
foo instanceof BigInt;
// β
typeof foo === 'bigint';// β
foo instanceof Symbol;
// β
typeof foo === 'symbol';// β
foo instanceof Array;
// β
Array.isArray(foo);// β
foo instanceof Function;
// β
typeof foo === 'function';// β
foo instanceof Object;
// β
Object.prototype.toString.call(foo) === '[object Object]';import is from '@sindresorhus/is';
// β
foo instanceof Map;
// β
is(foo) === 'Map';Type: 'loose' | 'strict'
Default: 'loose'
The matching strategy:
'loose'- Matches the primitive type (string,number,boolean,bigint,symbol) constructors,Function, andArray.'strict'- Matches all built-in constructors.
"unicorn/no-instanceof-builtins": [
"error",
{
"strategy": "strict"
}
]Type: string[]
Default: []
Specify the constructors that should be validated.
"unicorn/no-instanceof-builtins": [
"error",
{
"include": [
"WebWorker",
"HTMLElement"
]
}
]Type: string[]
Default: []
Specifies the constructors that should be excluded, with this rule taking precedence over others.
"unicorn/no-instanceof-builtins": [
"error",
{
"exclude": [
"String",
"Number"
]
}
]Type: boolean
Default: false
Specifies using Error.isError() to determine whether it is an error object.
"unicorn/no-instanceof-builtins": [
"error",
{
"strategy": "strict",
"useErrorIsError": true
}
]This option will be removed at some point in the future.