Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Declare explicit return types on functions
Annotate function return types instead of relying on inference, so the contract is clear and accidental changes are caught.
Bad example
| 1 | // Return type is inferred; the contract is implicit and can |
| 2 | // silently change if the body changes. |
| 3 | function parsePage(value: string) { |
| 4 | const page = Number(value); |
| 5 | return Number.isInteger(page) && page > 0 ? page : 1; |
| 6 | } |
Explanation (EN)
Without an annotation the reader must mentally execute the body to learn the return type, and an edit can change it without any signal.
Objašnjenje (HR)
Bez anotacije citatelj mora u glavi izvrsiti tijelo da sazna povratni tip, a izmjena ga moze promijeniti bez ikakvog signala.
Good example
| 1 | function parsePage(value: string): number { |
| 2 | const page = Number(value); |
| 3 | return Number.isInteger(page) && page > 0 ? page : 1; |
| 4 | } |
Explanation (EN)
An explicit return type documents the contract at a glance and makes the compiler flag any change that violates it.
Objašnjenje (HR)
Eksplicitan povratni tip dokumentira ugovor na prvi pogled i tjera kompajler da oznaci svaku promjenu koja ga krsi.
Notes (EN)
Most valuable on exported and public-API functions; trivial one-line inline callbacks can usually stay inferred.
Bilješke (HR)
Najkorisnije na izvezenim funkcijama i javnom API-ju; trivijalni jednolinijski inline callbackovi obicno mogu ostati inferirani.
Exceptions / Tradeoffs (EN)
Balance against prefer-inference-for-primitive-state: annotate return types on exported/public functions where the contract matters, not on trivial local helpers. Balance against infer-loader-data-types-from-implementation: annotate return types on regular functions and exported APIs for an explicit contract.