Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: typescript
typescriptdomeventstype-safetybrowser-api

Verify event target is a Node before DOM access

Use `instanceof Node` to safely narrow `event.target` types instead of unsafe casting with `as Node`.

PR: Fix/FCK-2261 - Fix issues with the Kapital frontpage widget #4151Created: Dec 7, 2025

Bad example

Old codets
1const handleClickOutside = (event: MouseEvent) => {
2 const wrapper = wrapperRef.current;
3
4 // ❌ BAD: Unsafe type assertion using 'as Node'
5 // event.target can be null or a generic EventTarget (like window) which lacks .contains()
6 if (wrapper && !wrapper.contains(event.target as Node)) {
7 setOpen(false);
8 }
9};

Explanation (EN)

Using `as Node` blindly forces TypeScript to accept the type, but it doesn't prevent runtime errors if `event.target` is null or not a DOM node (e.g., `window`). It bypasses type safety.

Objašnjenje (HR)

Korištenje `as Node` slijepo prisiljava TypeScript da prihvati tip, ali ne sprječava greške u izvođenju ako je `event.target` null ili nije DOM čvor (npr. `window`). Time se zaobilazi sigurnost tipova.

Good example

New codets
1const handleClickOutside = (event: MouseEvent) => {
2 const wrapper = wrapperRef.current;
3
4 // ✅ GOOD: Runtime check acts as a type guard
5 // It confirms event.target exists AND is a DOM Node before accessing .contains()
6 if (event.target instanceof Node && wrapper && !wrapper.contains(event.target)) {
7 setOpen(false);
8 }
9};

Explanation (EN)

Checking `instanceof Node` acts as a type guard. It ensures at runtime that the target is actually a DOM node, allowing TypeScript to safely infer the type and enabling access to methods like `.contains()`.

Objašnjenje (HR)

Provjera `instanceof Node` djeluje kao 'type guard'. Osigurava u vremenu izvođenja da je meta stvarni DOM čvor, što omogućuje TypeScriptu da sigurno zaključi tip i dopusti pristup metodama poput `.contains()`.