Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: typescript
typescripttype-safetyeventsdefensive-programminginvariant

Validate event targets with runtime checks

Avoid unsafe type casting on event.target; use instanceof checks or invariants to guarantee type safety at runtime.

PR: Feat/FCK-2245 - Cache Bellsheep and profile loaders with TanStack Query #343Created: Dec 10, 2025

Bad example

Old codets
1const listener = (event: Event) => {
2 // ❌ Unsafe: assumes target is always AbortSignal without checking
3 // If event.target is null or something else, this causes hard-to-debug runtime errors
4 const signal = event.target as AbortSignal;
5 console.log(signal.reason);
6};

Explanation (EN)

Using `as AbortSignal` silences TypeScript without verifying the actual object at runtime. If `event.target` is null or a different type, the code will fail unexpectedly downstream.

Objašnjenje (HR)

Korištenje `as AbortSignal` utišava TypeScript bez provjere stvarnog objekta tijekom izvođenja. Ako je `event.target` null ili drugi tip, kod će neočekivano zakazati u nastavku.

Good example

New codets
1import invariant from 'tiny-invariant';
2
3const listener = (event: Event) => {
4 // ✅ Safe: throws a clear error if the assumption is wrong
5 // TypeScript automatically narrows event.target to AbortSignal after this line
6 invariant(event.target instanceof AbortSignal, 'Event target must be an AbortSignal');
7
8 console.log(event.target.reason);
9};

Explanation (EN)

Using `invariant` or an `instanceof` check ensures the data matches expectations at runtime. It explicitly narrows the type for TypeScript, preventing crashes and making debugging easier.

Objašnjenje (HR)

Korištenje `invariant` ili `instanceof` provjere osigurava da podaci odgovaraju očekivanjima tijekom izvođenja. To eksplicitno sužava tip za TypeScript, sprječava rušenja i olakšava ispravljanje pogrešaka.