Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
typescriptreacthooksclean-codeinference

Rely on TypeScript inference for primitive state initialization

Avoid explicit generic type arguments for `useState` when the type can be correctly inferred from the initial primitive value.

PR: Feat/FCK-1623 - Adding eAvis widget to the sidebar #3643Created: Dec 8, 2025

Bad example

Old codetsx
1const [count, setCount] = useState<number>(0);
2const [isLoading, setIsLoading] = useState<boolean>(true);
3const [category, setCategory] = useState<string>('news');

Explanation (EN)

Explicitly adding generic types like `<number>` or `<string>` is redundant when initializing with a primitive. It adds visual noise without improving type safety.

Objašnjenje (HR)

Eksplicitno dodavanje generičkih tipova poput `<number>` ili `<string>` je suvišno kod inicijalizacije primitivima. Dodaje vizualni šum bez poboljšanja sigurnosti tipova.

Good example

New codetsx
1const [count, setCount] = useState(0);
2const [isLoading, setIsLoading] = useState(true);
3const [category, setCategory] = useState('news');

Explanation (EN)

By omitting the generic, the code is cleaner and cleaner. TypeScript automatically infers the type from the initial value (e.g., `0` implies `number`).

Objašnjenje (HR)

Izostavljanjem generika kod je čišći. TypeScript automatski zaključuje tip iz početne vrijednosti (npr. `0` podrazumijeva `number`).

Notes (EN)

Explicit types are only necessary when the initial value is `null`, `undefined`, or an empty array (where inference might be `never[]`), or when using Union types.

Bilješke (HR)

Eksplicitni tipovi su potrebni samo kada je početna vrijednost `null`, `undefined` ili prazan niz (gdje bi zaključak mogao biti `never[]`), ili kada se koriste Union tipovi.