Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

typed-query-selector

g-plane4.6mMIT2.12.0TypeScript support: included

Better typed querySelector and querySelectorAll.

readme

🏷 Typed querySelector

querySelector and querySelectorAll functions with better typing by leveraging TypeScript 4.1 template literal type.

💿 Install

npm i -D typed-query-selector

🍉 Usage

Automatic shim

All you need to do is to import this module, then the querySelector and querySelectorAll function will be enhanced.

This module only works at type level and doesn't have any runtime code.

import 'typed-query-selector'

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

document.querySelector('div#app > form#login') // ==> HTMLFormElement

document.querySelectorAll('span.badge') // ==> NodeListOf<HTMLSpanElement>

anElement.querySelector('button#submit') // ==> HTMLButtonElement

Playground

The example above assumes you're using bundlers or build tools with transpilers, however, sometimes this may not match your situation. For example, running tsc or Babel out of bundlers. In this case, you can import this library like this:

import type {} from 'typed-query-selector'

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

Playground

This looks ugly but it works.

If you aren't going to use ES Modules you can modify your tsconfig.json, however this is NOT recommended, unless you know what you're doing.

{
  "compilerOptions": {
    "types": ["typed-query-selector"]
  }
}

Strict mode

Available in v2.3+

In strict mode, the selector parser will perform additional syntax checks on input string. If there're syntax errors, return type will be never instead of Element.

Example usage:

import 'typed-query-selector/strict'

const element = document.querySelector('div[test') // return `never`

This feature won't be enabled by default and you can opt-in. If you want to enable this, change import entry:

- import 'typed-query-selector'
+ import 'typed-query-selector/strict'

That's all. If you pass an invalid selector, because it returns never, TypeScript will prevent you from accessing properties/methods on element or using element at somewhere.

Note that it doesn't guarantee that it can detect every kind of syntax errors, since such parser will become very complex and compilation performance may go bad.

Use the parser

If you just want to use the selector parser itself, we've exported for you:

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

type MyElement = ParseSelector<'form#login'>

Playground

Please note that you should import typed-query-selector/parser, not typed-query-selector. This is safe because this import doesn't patch to the querySelector and querySelectorAll function.

Sometimes, you may want to specify another fallback type (such as HTMLElement, not default Element type) when failed to parse selector or failed to look up, you can pass a fallback type as the second type parameter:

Available in v2.4+

import type { ParseSelector } from 'typed-query-selector/parser'

type MyElement = ParseSelector<'unknown-tag', HTMLElement> // ==> HTMLElement

Playground

💡 Supported Use Cases

With class, ID, pseudo class or attribute

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

Playground

Even mix them:

import 'typed-query-selector'

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

Playground

And with :is() or :where():

Available in v2.5+

import 'typed-query-selector'

document.querySelector(':is(div#id, span.class[k=v])') // ==> HTMLDivElement | HTMLSpanElement

document.querySelector(':where(div#id, span.class[k=v])') // ==> HTMLDivElement | HTMLSpanElement

Playground

Combinators

import 'typed-query-selector'

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

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

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

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

Playground

Grouping selectors

import 'typed-query-selector'

document.querySelector('div, span') // ==> HTMLDivElement | HTMLSpanElement

Playground

Fallback

Custom Elements

If you passed an unknown tag, it will fall back to Element.

import 'typed-query-selector'

document.querySelector('my-web-component') // ==> Element

However, you can override it by specifying a concrete type as a type argument.

document.querySelector<MyComponent>('my-web-component') // ==> MyComponent

Playground

Alternatively, you can use global augmentation and interface merging to extend HTMLElementTagNameMap with your custom elements.

declare global {
  interface HTMLElementTagNameMap {
    'my-web-component': MyComponent
  }
}

document.querySelector('my-web-component') // ==> MyComponent

Playground

Invalid selector

When passing an invalid selector which causes parsing error, it will fall back to Element.

import 'typed-query-selector'

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

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

However, if you're using strict mode, all querySelector calls above will return never type. This can stop you from misusing it.

import 'typed-query-selector/strict'

const el = document.querySelector('div#app >')
el.className // TypeScript will report error when compiling

🔩 Technical Details

Why returns never in strict mode?

In runtime, if you pass an invalid selector string to querySelector or querySelectorAll function, it will throw an error instead of returning null or undefined or anything else. For details, please read TypeScript Handbook.

  • Type Gymnastics - Collection of wonderful TypeScript type gymnastics code snippets.

📃 License

MIT License

Copyright (c) 2020-present Pig Fang

changelog

Change Log

Unreleased

v2.12.0

  • Added support of special case for custom pseudo element selector.

v2.11.4

  • Fixed parsing unclosed attribute selector (such as a[href).
  • Fixed parsing bare pseudo class or element selectors.

v2.11.3

  • Fixed for TypeScript 5.5.

v2.11.2

  • Fixed handling unknown incorrectly. (Fix #36)

v2.11.1

  • Fixed for TypeScript 5.4. (Fix #35)

v2.11.0

  • Added .js extension in import statements.

v2.10.1

  • Setup publishing on GitHub Actions. No code changes.

v2.10.0

  • Reverted to fallback to Element, not HTMLElement.

v2.9.2

  • Fixed regression of specifying fallback type. (Fix #33)

v2.9.1

  • Fixed some cases of :is() and :where() by rewriting the expanding logic.
  • Fixed template with dynamic interpolation.

v2.9.0

  • Added fallback support to strict parser.
  • Fallback to HTMLElement for HTMLElement, Document and DocumentFragment. (Close #29)

v2.8.1

  • Fixed passing string type as argument in strict parser.
  • Fixed some cases of :is() and :where().

v2.8.0

  • Export "strict" parser. (Close #25)
  • Removed exported private type ParseSelectorToTagNames.

v2.7.0

  • Require TypeScript 4.7.
  • Fixed invalid result after expanding :is or :where function. (Fix #23)

v2.6.1

  • Fixed support of TypeScript 4.5.

v2.6.0

  • Support .closest() method on Element. (Close #16)

v2.5.3

  • Fixed a regression bug which is introduced in v2.5.2.

v2.5.2

  • Fixed attribute syntax in :is() and :where(). (Fix #15)

v2.5.1

  • Fixed regression bug: fallback type doesn't work. (Fix #14)

v2.5.0

  • Added support for :is() and :where() pseudo-classes. (Fix #13)

v2.4.1

  • Fixed return type in shim can be cast.

v2.4.0

  • Fixed errors with disabled skipLibCheck.
  • Allowed to specify custom fallback type when failed to parse selector. (only for ParseSelector type, not for querySelector function)

v2.3.0

  • Treat empty string as syntax error.
  • Treat empty attribute [] as syntax error.
  • Added namespace prefix support.
  • Added strict mode.
  • Fixed precedences between combinators and groupings.

v2.2.4

  • Process quotes separately.
  • Added simple selector syntax check.

v2.2.3

  • Refactor types.

v2.2.2

  • Fixed possible OOM.
  • Fixed arbitrary content in attribute.

v2.2.1

  • Fixed multiline with starting tabs or spaces.

v2.2.0

  • Support tabs in selector string.
  • Support pseudo-classes in selector.

v2.1.1

  • Fixed more kinds of whitespace characters in selector.
  • Fixed combinator characters in attribute of selector.

v2.1.0

  • Added types field to package.json.

v2.0.0

  • Breaking change: querySelector and querySelectorAll from this package are removed. You just need to import this package then use document.querySelector normally. Check out readme for detailed usage.

v1.1.0

  • Publish declaration map.

v1.0.0

  • Initial release.