Skip to content

Commit be17ebb

Browse files
committed
Completed work on 08
1 parent fc7cd98 commit be17ebb

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

exercises/08-nonNullQuerySelector.exercise.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
*/

exercises/08-nonNullQuerySelector.solutions.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,18 @@
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
*/

0 commit comments

Comments
 (0)