All Projects → g-plane → Typed Query Selector

g-plane / Typed Query Selector

Licence: mit
Better typed `querySelector` and `querySelectorAll`.

Programming Languages

typescript
32286 projects

Labels

Projects that are alternatives of or similar to Typed Query Selector

Link Grammar
The CMU Link Grammar natural language parser
Stars: ✭ 286 (-9.49%)
Mutual labels:  parser
Bblfshd
A self-hosted server for source code parsing
Stars: ✭ 297 (-6.01%)
Mutual labels:  parser
Demofile
Node.js library for parsing Counter-Strike: Global Offensive demo files
Stars: ✭ 305 (-3.48%)
Mutual labels:  parser
Php Apk Parser
Read basic info about an application from .apk file.
Stars: ✭ 290 (-8.23%)
Mutual labels:  parser
Termimad
A library to display rich (Markdown) snippets and texts in a rust terminal application
Stars: ✭ 293 (-7.28%)
Mutual labels:  parser
App Info Parser
A javascript parser for parsing .ipa or .apk files. IPA/APK文件 js 解析器
Stars: ✭ 298 (-5.7%)
Mutual labels:  parser
Jpegsnoop
JPEGsnoop: JPEG decoder and detailed analysis
Stars: ✭ 282 (-10.76%)
Mutual labels:  parser
Algebraicengine Fraction
a calculating engine~
Stars: ✭ 311 (-1.58%)
Mutual labels:  parser
Hquery.php
An extremely fast web scraper that parses megabytes of invalid HTML in a blink of an eye. PHP5.3+, no dependencies.
Stars: ✭ 295 (-6.65%)
Mutual labels:  parser
Jspoon
Annotation based HTML to Java parser + Retrofit converter
Stars: ✭ 306 (-3.16%)
Mutual labels:  parser
Length.js
📏 JavaScript library for length units conversion.
Stars: ✭ 292 (-7.59%)
Mutual labels:  parser
Raw Body
Get and validate the raw body of a readable stream
Stars: ✭ 292 (-7.59%)
Mutual labels:  parser
Pyresparser
A simple resume parser used for extracting information from resumes
Stars: ✭ 297 (-6.01%)
Mutual labels:  parser
Exifer
A lightweight Exif meta-data decipher.
Stars: ✭ 290 (-8.23%)
Mutual labels:  parser
Demoinfo
A library to analyze CS:GO demos in C#
Stars: ✭ 306 (-3.16%)
Mutual labels:  parser
Sql Parser
A validating SQL lexer and parser with a focus on MySQL dialect.
Stars: ✭ 284 (-10.13%)
Mutual labels:  parser
Psd.rb
Parse Photoshop files in Ruby with ease
Stars: ✭ 3,092 (+878.48%)
Mutual labels:  parser
Astroid
A common base representation of python source code for pylint and other projects
Stars: ✭ 310 (-1.9%)
Mutual labels:  parser
Regex
The Hoa\Regex library.
Stars: ✭ 308 (-2.53%)
Mutual labels:  parser
Exprtk
C++ Mathematical Expression Parsing And Evaluation Library
Stars: ✭ 301 (-4.75%)
Mutual labels:  parser

🏷 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

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 do 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 } from 'typed-query-selector/parser'

type MyElement = ParseSelector<'form#login'>

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

💡 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

Even mix them:

import 'typed-query-selector'

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

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

Grouping selectors

import 'typed-query-selector'

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

Fallback

Web Components

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

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].