• Stars
    star
    718
  • Rank 63,070 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Better typed `querySelector` and `querySelectorAll`.

🏷 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, but you can override it by specifying concrete type.

import 'typed-query-selector'

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

document.querySelector<MyComponent>('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.

🔗 Related

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

📃 License

MIT License

Copyright (c) 2020-present Pig Fang

More Repositories

1

zsh-yarn-autocompletions

Zsh plugin for Yarn autocompletions.
Rust
578
star
2

type-gymnastics

Collection of wonderful TypeScript type gymnastics code snippets.
TypeScript
362
star
3

tiny-package-manager

Learn how npm or Yarn v1 works.
TypeScript
344
star
4

rize

High-level, fluent and chainable API provided library for puppeteer.
TypeScript
176
star
5

pnpm-shell-completion

Complete your pnpm command fastly.
Shell
107
star
6

swc-plugin-vue-jsx

SWC plugin for transforming Vue JSX.
Rust
91
star
7

markup_fmt

Configurable HTML, Vue, Svelte, Astro, Angular, Jinja, Twig, Nunjucks and Vento formatter with dprint integration.
Rust
90
star
8

malva

Configurable, smart and fast CSS, SCSS, Sass and Less formatter with dprint integration.
Rust
70
star
9

TypeCake

TypeCake is a language that compiles to TypeScript types. (WIP)
TypeScript
50
star
10

raffia

CSS, Sass, SCSS and Less parser, all in one.
Rust
49
star
11

swc-css-playground

Playground for SWC CSS.
Svelte
29
star
12

icd

Powerful `cd` command with fuzzy-search tool.
Shell
27
star
13

pnpm-docker

Docker images that includes pnpm.
Dockerfile
17
star
14

flac.wasm

Run official FLAC tools `flac` and `metaflac` as WebAssembly, on browsers or Deno.
TypeScript
17
star
15

node-green

Check Node.js ECMAScript compatibility.
TypeScript
17
star
16

swc-playground

Repository has been transferred to swc-project/swc-playground.
TypeScript
16
star
17

pretty_yaml

Semi-tolerant and configurable YAML formatter with dprint integration.
Rust
16
star
18

node-green-cli

CLI for "node-green" module.
TypeScript
12
star
19

swc-plugin-react-remove-properties

SWC plugin for removing React properties.
Rust
12
star
20

pluggable-babel-eslint

Pluggable babel-eslint.
JavaScript
8
star
21

pazza

Parser combinators library which works on browsers, Deno and Node.js.
TypeScript
7
star
22

eslint-playground

Creating an ESLint rule instantly.
TypeScript
7
star
23

dgut-network-login

自动登录 DGUT 的校园网。
JavaScript
5
star
24

matchable

`matchable` provides a convenient enum for checking if a piece of text is matching a string or a regex.
Rust
5
star
25

id3

Library for manipulating ID3 tag.
TypeScript
4
star
26

acorn-typescript

Acorn plugin for parsing TypeScript.
JavaScript
3
star
27

simple-base

A simple base36/base58 converter.
TypeScript
3
star
28

hexo-theme-straight

Clean and simple Hexo theme.
Jinja
3
star
29

pretty_graphql

Configurable GraphQL formatter.
Rust
3
star
30

web-guessing-game

Guess logos of JavaScript/CSS libraries.
Svelte
2
star
31

cue-splitter

Split audio into different tracks with Cue Sheet in comprehensive UI.
TypeScript
2
star
32

eslint-formatter-beauty

Beautiful ESLint formatter.
TypeScript
1
star
33

css_dataset

Collections of CSS dataset about functions, properties, etc.
Rust
1
star
34

bs-plugin-kumiko-stickers

PHP
1
star
35

eslint-config-gplane

Shareable ESLint config for Pig Fang's projects
JavaScript
1
star
36

raffia-playground

AST viewer for Raffia.
TypeScript
1
star
37

rollup-on-deno

Run Rollup on Deno.
TypeScript
1
star
38

tiny_pretty

Tiny implementation of Wadler-style pretty printer.
Rust
1
star
39

blog

1
star
40

vscode-beefweb

Control your foobar2000 or deadbeef via beefweb server.
TypeScript
1
star
41

malva-playground

Format CSS/Sass/SCSS/Less code with Malva on browsers.
Svelte
1
star