Last active
August 12, 2024 09:39
-
-
Save esamattis/532f0f6648e74e7237d9bbd9fc54d681 to your computer and use it in GitHub Desktop.
jsdoc type guards for dom elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @template {keyof HTMLElementTagNameMap} T | |
* @param {any} el | |
* @param {T} elName | |
* @returns {el is HTMLElementTagNameMap[T]} | |
*/ | |
function isElement(el, elName) { | |
return el?.constructor?.name === elName; | |
} | |
/** | |
* @param {any} el | |
* @returns {el is HTMLElement} | |
*/ | |
function isHTMLElement(el) { | |
const name = el?.constructor?.name; | |
if (!name) { | |
return false; | |
} | |
if (name === "HTMLElement") { | |
return true; | |
} | |
return isHTMLElement(Object.getPrototypeOf(el)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment