1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

querySelectorの返り値の型を絞り込む関数を作る

Last updated at Posted at 2024-03-10

背景

querySelector(),querySelectorAll()で型がElement,NodeListOf<Element>になって毎回型チェックをするのが手間だなと感じていました。

querySelectorの返り値の型を絞り込む関数

const safeQuerySelector = <T extends Element>(
  root: Element | Document,
  selector: string,
  expectedElementType: { new (): T; prototype: T }
): T | null => {
  const elm = root.querySelector(selector);
  if (elm instanceof expectedElementType) return elm;
  return null;
};

const a = safeQuerySelector(document, "div", HTMLDivElement); //HTMLDivElement|null

今後の課題

第二引数のselectorの文字列がセレクタの構文として問題があるときにnever型で返すようにしたいです。

以前調べた typed-query-selector のstrictモードのようなものです。

最後に

  • ジェネリクスを使いこなせるようになりたいです!
  • typed-query-selectorのソースが勉強になるので眺めようと思います
  • あとはブルーベリー本も読みたいです
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?