Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

typed-query-selector

> 编程语言
Open source

Better typed `querySelector` and `querySelectorAll`.

785 stars0 likes0 views
WebsiteGitHub

About

Better typed `querySelector` and `querySelectorAll`.

Typed querySelector

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

Install

bash
npm i -D typed-query-selector

Usage

Automatic shim

You can modify your tsconfig.json as below because this package contains type definitions only. This is recommended since TypeScript 6.0.

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

Alternatively you can import this package if you're using bundler. This package only works at type level and doesn't have any runtime code.

typescript
import 'typed-query-selector'

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

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

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

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

Playground

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:

typescript
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, modify tsconfig.json:

diff
 {
   "compilerOptions": {
-    "types": ["typed-query-selector"]
+    "types": ["typed-query-selector/strict"]
   }
 }

or change import entry:

diff
- 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:

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

type MyElement = ParseSelector

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+

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

type MyElement = ParseSelector // ==> HTMLElement

Playground

Supported Use Cases

With class, ID, pseudo class or attribute

typescript
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:

typescript
import 'typed-query-selector'

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

Playground

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

Available in v2.5+

typescript
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

typescript
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

typescript
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.

typescript
import 'typed-query-selector'

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

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

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

Playground

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

typescript
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.

typescript
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.

typescript
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.

Related

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

License

MIT License

Copyright (c) 2020-present Pig Fang

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptparsertypescript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言