TypeScript Code Style
Strict, opinionated rules. Follow these to write correct code on the first draft.
Control Flow
- Early returns for guard clauses — return early for error/edge cases to keep main logic flat
- Always use block bodies for
ifwithreturn— neverif (!x) return;on one line - Prefer positive conditions — check what should happen, not what shouldn't. Does NOT apply to guard clauses, where negative checks are expected
- No
elseafterreturn— if a branch returns, the next block needs noelse switchover chainedif— when checking the same variable against multiple values
Type Safety
- No
any— forbidden. Useunknownfor uncertain types, generics to preserve/relate types - No non-null assertions (
!) — forbidden. Use optional chaining (?.) or guard clauses - Minimize
ascasting — fix types at the source. Use generics,satisfies, or type guards instead - Generics over broad types — prefer generic parameters over accepting broad types and casting results
- Let TypeScript infer return types — only annotate when needed (public APIs, recursion, or when inference produces the wrong type)
Enums
No enums — forbidden. Use as const objects with derived types:
const Status = {
Active: 'active',
Inactive: 'inactive',
} as const;
type Status = (typeof Status)[keyof typeof Status];
Naming
- Be descriptive — prefer specificity over brevity.
activeUsersnotdata,sortByDatenotprocess - No
I/Tprefixes —UsernotIUser,ConfignotTConfig
Converted and distributed by TomeVault — claim your Tome and manage your conversions.