Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: no-instanceof-builtin-object #2452

Open
zanminkian opened this issue Sep 16, 2024 · 0 comments
Open

Rule proposal: no-instanceof-builtin-object #2452

zanminkian opened this issue Sep 16, 2024 · 0 comments

Comments

@zanminkian
Copy link
Contributor

zanminkian commented Sep 16, 2024

Description

instanceof operator in JavaScript has some limitations.

To detect the type of a variable, we should encourage user to use:

  • typeof operator
typeof foo === 'string' // detect whether foo is string
  • node:util/types module (for Node)
import {isNumberObject, isMap} from 'node:util/types';
isNumberObject(new Number(123)) // true
isNumberObject(123) // false
isMap(new Map()) // true
  • @sindresorhus/is module (for browser)
import is from '@sindresorhus/is';
is(new Map()) === 'Map' // true

Therefore, builtin objects like Map/Promise/Error can be detected by typeof, node:util/types and @sindresorhus/is. Should not use instanceof.

Rule no-instanceof-array can be removed if this rule is implemented.

Fail

foo instanceof Array
foo instanceof Map
foo instanceof Promise

Pass

import types from 'node:util/types'
Array.isArray(foo)
types.isMap(foo)
types.isPromise(foo)
import is from '@sindresorhus/is'
is(foo) === 'Array'
is(foo) === 'Map'
is(foo) === 'Promise'

Proposed rule name

no-instanceof-builtin-object

Additional Info

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant