Skip to content

Commit c1e5e3f

Browse files
authored
Validate internal selectors via TypeScript (#224)
1 parent 8d84e1e commit c1e5e3f

3 files changed

Lines changed: 27 additions & 79 deletions

File tree

index.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,24 @@
1+
import type {StrictlyParseSelector} from 'typed-query-selector/parser.js';
12
import reservedNames from 'github-reserved-names/reserved-names.json' with {type: 'json'};
23
import {addTests} from './collector.ts';
34

4-
const $ = <E extends Element>(selector: string) => document.querySelector<E>(selector);
5-
const exists = (selector: string) => Boolean($(selector));
5+
function $<Selector extends string, Selected extends Element = StrictlyParseSelector<Selector>>(
6+
selector: Selector,
7+
): Selected | undefined;
8+
function $<Selected extends Element = HTMLElement>(
9+
selector: string,
10+
): Selected | undefined;
11+
function $<Selected extends Element>(selector: string): Selected | undefined {
12+
return document.querySelector<Selected>(selector) ?? undefined;
13+
}
14+
15+
function exists<Selector extends string, Selected extends Element = StrictlyParseSelector<Selector>>(
16+
selector: Selector,
17+
): Selected extends never ? never : boolean;
18+
function exists(selector: string): boolean;
19+
function exists(selector: string): boolean {
20+
return Boolean(document.querySelector(selector));
21+
}
622

723
/**
824
* Waits for a detection to return true by repeatedly checking it on each animation frame.

package-lock.json

Lines changed: 8 additions & 77 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
"svelte-check": "^4.3.5",
5757
"ts-morph": "^27.0.2",
5858
"tsx": "^4.21.0",
59+
"typed-query-selector": "^2.12.0",
5960
"typescript": "5.9.3",
6061
"vite": "^7.3.1",
6162
"vitest": "^4.0.17",

0 commit comments

Comments
 (0)