Skip to content

Rule proposal: prefer-instanceof-element #1574

Open
@kidonng

Description

@kidonng

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
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions