3 ms·
Here's a stretch goal: use typescript template string magic to correctly infer the type of elements. For instance you can statically infer that $('div#name') wi
by chmod775 2y ago
Here's a stretch goal: use typescript template string magic to correctly infer the type of elements. For instance you can statically infer that $('div#name') will be a HTMLDivElement.
- hinkley 2y agoElixir and a few other languages have the pattern matching and type system that could pull that off but not a lot of languages do. Can you do that in typescript? I don’t see how.
- dimava 2y agoYou can, using `function $<S>(sel: S | `${S}${ ' '|'#'|'.'|'[' }${string}`): HTMLElementMap[T];` or export type inferSelectorElementName<sel extends selector> = | string extends sel ? HTMLElement : sel extends `${infer A},${infer B}` ? inferSelectorElementName<A | B> : sel extends `${infer A}${'.' | '[' | '#'}${infer _}` ? inferSelectorElementName<A> : sel export type inferElementFromSelector<sel extends selector> = | string extends sel ? HTMLElement : inferSelectorElementName<sel> extends infer S ? S extends '' ? HTMLElement : S extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[S] : never : never TS types may go quite deep Check Arktype library [https://arktype.io/ https://arktype.io/], it's type definitions are basically a Typescript written in JSON const user = type({ name: "string", platform: "'android' | 'ios'", "version?": "number | string" })
- totallykvothe 2y agoYou definitely can do that in TypeScript. The kinds of things you can do with generic inference and string literals are crazy
- norskeld 2y agoTypeScript's type system is Turing complete, so you can not only do that, but also some insane stuff like: - A SQL database implemented purely in TypeScript type system (https://github.com/codemix/ts-sql https://github.com/codemix/ts-sql) - Chess implemented entirely in TypeScript (and Rust) type systems (https://github.com/Dragon-Hatcher/type-system-chess https://github.com/Dragon-Hatcher/type-system-chess) - Lambda calculus in TypeScript type system (https://ayazhafiz.com/articles/21/typescript-type-system-lambda-calculus https://ayazhafiz.com/articles/21/typescript-type-system-lam...)
- hoten 2y agoThe package is called `typed-query-selector`. Here it is in action: https://github.com/GoogleChrome/lighthouse/blob/main/types/internal/query-selector.d.ts https://github.com/GoogleChrome/lighthouse/blob/main/types/i...