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: prefer-instanceof-element #1574

Open
kidonng opened this issue Nov 3, 2021 · 4 comments
Open

Rule proposal: prefer-instanceof-element #1574

kidonng opened this issue Nov 3, 2021 · 4 comments

Comments

@kidonng
Copy link
Contributor

kidonng commented Nov 3, 2021

Checking the type of an element via element.tagName === 'name' doesn't give you type guard and you have to use optional chain (or ! a.k.a. Typescript's non-null assertion operator) if the element can be undefined or null.

Some elements have a corresponding JavaScript interface (e.g. HTMLImageElement for <img>), one can also use instanceof to check the element type without the aforementioned shortcomings.

An real life example is: 574d442 (#5036)

Fail

if (event.target.parentElement?.tagName === 'img') {
	return (target as HTMLImageElement).src
}

Pass

if (event.target.parentElement instanceof HTMLImageElement) {
	return target.src
}
@sindresorhus
Copy link
Owner

I think the rule scope and name should be more narrow. instanceof is generally not the best solution for most type-checks.

This will also most likely get solved in TypeScript at some point: microsoft/TypeScript#38839

@kidonng kidonng changed the title Rule proposal: prefer-instanceof Rule proposal: prefer-instanceof-element Nov 3, 2021
@kidonng
Copy link
Contributor Author

kidonng commented Nov 3, 2021

I think the rule scope and name should be more narrow. instanceof is generally not the best solution for most type-checks.

How about prefer-instanceof-element?

This will also most likely get solved in TypeScript at some point: microsoft/TypeScript#38839

I'm aware of that but it will probably take forever. And there are benefits outside TS too.

@sindresorhus
Copy link
Owner

I would name it prefer-instanceof-dom-element since element is a general term, for example, an element in a collection.

@sindresorhus
Copy link
Owner

I'm aware of that but it will probably take forever. And there are benefits outside TS too.

What are the non-TS benefits?

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

2 participants