querySelector wrapper #17930
-
I have a wrapper for function qs(selector: string) {
const elm = document.querySelector(selector)
if (!elm) throw new Error(`'${sel}' is not in dom`)
return elm
}
const canvas = qs('canvas')
canvas.getContext('2d') Of course I get Is there a way to make I tried this: function qs<T extends Parameters<typeof document.querySelector>[0]>(
selector: T
): ReturnType<typeof document.querySelector<typeof selector>> {
return document.querySelector(selector)
} But I get these errors:
In others words, I want the variable
|
Beta Was this translation helpful? Give feedback.
Answered by
JonghwanWon
Oct 29, 2022
Replies: 1 comment
-
hello, @yukulele I hope this solution help you. function qs<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;
function qs<K extends keyof SVGElementTagNameMap>(selectors: K): SVGElementTagNameMap[K] | null;
function qs<E extends Element = Element>(selectors: string): E | null;
function qs(selectors: Parameters<typeof document['querySelector']>[0]) {
const elm = document.querySelector(selectors);
if (!elm) throw new Error(`'${selectors}' is not in dom.`);
return elm;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
yukulele
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello, @yukulele
I hope this solution help you.