File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -286,3 +286,48 @@ const bodyElem = document.querySelector("body");
286286 *
287287 * Solution #5
288288 */
289+
290+ /**
291+ * 🛠 Add an overload to nonNullQuerySelector which matches
292+ * document.querySelector.
293+ *
294+ * You'll need to use HTMLElementTagNameMap, and you'll need a
295+ * generic.
296+ *
297+ * Docs: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads
298+ *
299+ * Solution #6
300+ *
301+ * ✅ Incredibly, the error disappeared.
302+ */
303+
304+ /**
305+ * 🚁 Hover result:
306+ *
307+ * const result = nonNullQuerySelector("body");
308+ * ^ 🚁
309+ *
310+ * The result is HTMLBodyElement! Which means that:
311+ *
312+ * console.log(e.gamepad);
313+ * ^ 🚁
314+ *
315+ * e is GamepadEvent! Which, as we know, has the gamepad
316+ * property on it.
317+ */
318+
319+ /**
320+ * 💡 Sometimes, type errors are not as they appear. This one
321+ * took us through function overloads, a deep dive into
322+ * lib.dom.d.ts, and generics. It turned out that the fix
323+ * was in a whole other section than the highlighted error.
324+ */
325+
326+ /**
327+ * 🕵️♂️ Stretch goal 1: Add another overload which uses
328+ * SVGElementTagNameMap to handle SVG elements, and test
329+ * that it works using:
330+ *
331+ * const clipPathElement = nonNullQuerySelector('clipPath');
332+ * ^ 🚁 Should be SVGClipPathElement
333+ */
Original file line number Diff line number Diff line change 7575 * widest third overload of document.querySelector, meaning that
7676 * the elements we return will always be Element, never
7777 * HTMLBodyElement.
78+ *
79+ * querySelector<E extends Element = Element>(selectors: string): E | null;
80+ *
81+ * 💡 In order to overcome this problem, we're going to need to
82+ * mirror document.querySelector's overloads with
83+ * nonNullQuerySelector. Otherwise, we'll always just trigger
84+ * that last overload and our inference won't work.
85+ *
86+ * #6
87+ *
88+ * export function nonNullQuerySelector<K extends keyof HTMLElementTagNameMap>(
89+ * tag: K,
90+ * ): HTMLElementTagNameMap[K];
91+ * export function nonNullQuerySelector(tag: string) {
7892 */
You can’t perform that action at this time.
0 commit comments