LoginSignup
1
0

typed-query-selector について調べてみる

Last updated at Posted at 2024-03-09

1. 背景

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

const a = document.querySelectorAll('div#app');

image.png

以下の記事でtyped-query-selectorというライブラリを知りました。

2. typed-query-selector

querySelector,querySelectorAllの型推論を向上させたライブラリです。

上の型定義ファイルを見るとreadmeに記載されていた

querySelectorとquerySelectorAll関数は、TypeScript 4.1のテンプレート・リテラル型を活用することで、より良い型付けができるようになった

が理解できると思います。

2.1.install

npm i -D typed-query-selector

ビルドツールやトランスパイラを使用されてる場合はこれだけで設定完了です。

2.2.使ってみる

querySelector

import 'typed-query-selector';

const a = document.querySelector('div#app');

image.png

querySelectorAll

import 'typed-query-selector';

const a = document.querySelectorAll('div#app');

image.png

2.3. 対応しているユースケース

class属性, id属性, 疑似class, その他属性

import 'typed-query-selector'

document.querySelector('div.container') // ==> HTMLDivElement

document.querySelector('div#app') // ==> HTMLDivElement

document.querySelector('input[name=username]') // ==> HTMLInputElement

document.querySelector('input:first-child') // ==> HTMLInputElement```

組み合わせ

import 'typed-query-selector'

document.querySelector('body div') // ==> HTMLDivElement

document.querySelector('body > form') // ==> HTMLFormElement

document.querySelector('h1 + p') // ==> HTMLParagraphElement

document.querySelector('h2 ~ p') // ==> HTMLParagraphElement

2.4. Strictモード

Strictモードではセレクタ・パーサは入力文字列に対して追加の構文チェックを行います。
構文エラーがあった場合、戻り値の型はElementではなくneverになります。

import 'typed-query-selector/strict'

const element = document.querySelector('div[test') 

image.png

全ての子構文エラーを検出できるとは限らないとのことです。
パーサーが非常に複雑になり、コンパイルのパフォーマンスが低下する可能性がある為だそうです。

2.5. parser単体でも使える

import type {
  ParseSelector,
  StrictlyParseSelector, // or use the strict parser
} from 'typed-query-selector/parser'

type MyElement = ParseSelector<'form#login'> //HTMLFormElement 

最後に

querySelector,querySelectorAllを使用するなら入れて損はないと思いました!
strictモードの構文チェックも良いなと思いました

参考

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