Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: typescript
clean-codeerror-handlingtypescriptvalidation

Prefer invariant over manual error throwing

Use invariant utilities to assert conditions and narrow types instead of verbose manual checks.

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

Bad example

Old codets
1function processUser(user: User | null) {
2 if (!user) {
3 throw new Error('User is required to process data');
4 }
5
6 if (!(user.age > 18)) {
7 throw new Error('User must be an adult');
8 }
9
10 // logic...
11}

Explanation (EN)

Manual checks using 'if' statements and 'throw new Error' are verbose and add visual noise. They require reading the negative condition to understand the requirement.

Objašnjenje (HR)

Ručne provjere pomoću 'if' naredbi i 'throw new Error' su opširne i stvaraju vizualnu buku. Zahtijevaju čitanje negativnog uvjeta kako bi se razumio zahtjev.

Good example

New codets
1import invariant from 'tiny-invariant';
2
3function processUser(user: User | null) {
4 invariant(user, 'User is required to process data');
5 invariant(user.age > 18, 'User must be an adult');
6
7 // logic...
8}

Explanation (EN)

Using 'invariant' is concise, clearly states the positive expectation, and automatically narrows TypeScript types. It also often optimizes error messages for production builds.

Objašnjenje (HR)

Korištenje 'invariant' funkcije je sažeto, jasno izražava pozitivno očekivanje i automatski sužava TypeScript tipove. Često i optimizira poruke o greškama za produkcijska okruženja.

Notes (EN)

Popular libraries include 'tiny-invariant' for frontend/general use and 'node:assert' for Node.js backends.

Bilješke (HR)

Popularne biblioteke uključuju 'tiny-invariant' za frontend/općenitu upotrebu i 'node:assert' za Node.js backend.