ajquery.js icon indicating copy to clipboard operation
ajquery.js copied to clipboard

types: how to get more specific returns than just "Element"?

Open coolaj86 opened this issue 5 months ago • 1 comments

Problem

let input = $("input");
if (!input) {
  throw new Error('no input element selected');
}
input.value = "foo"; // E: Property 'value' does not exist on type 'Element'.

Here's a basic type definition that's unfortunately quite wrong:

/**
 * Select first matching element, just like console $
 * @param {String} cssSelector
 * @param {ParentNode} [$parent=document]
 */
function $(cssSelector, $parent = document) {
  let $child = $parent.querySelector(cssSelector);
  return $child;
}

/**
 * Select all matching child elements as a JS Array, just like console $$
 * @param {String} cssSelector
 * @param {ParentNode} [$parent=document]
 */
function $$(cssSelector, $parent = document) {
  let $children = $parent.querySelectorAll(cssSelector);
  let children = Array.from($children);
  return children;
}

coolaj86 avatar Aug 29 '24 22:08 coolaj86