TypeScript Code Conventions — Section Outline
-
Naming Conventions
- Variables and constants
- Functions and methods
- Classes and constructors
- Interfaces and types
- Enums and enum members
- Generic type parameters
- Files and modules
-
Type System
- Type vs. interface
- Explicit vs. inferred types
- Union and intersection types
- Literal types
- Template literal types
- Utility types (
Partial,Pick,Omit, etc.) unknownvs.anyvs.never- Type assertions and casting
- Type guards and narrowing
- Branded / nominal types
-
Strict Mode
- Required
tsconfigflags strictNullChecksrulesnoUncheckedIndexedAccessexactOptionalPropertyTypes
- Required
-
Interfaces and Classes
- When to use a class vs. a plain object
- Access modifiers (
public,private,protected,readonly) - Abstract classes
- Implementing interfaces
- Constructor patterns
-
Generics
- When to use generics
- Constraints (
extends) - Default type parameters
- Avoiding over-generalization
-
Enums
const enumvs. regularenum- String enums vs. numeric enums
- Alternatives to enums (union types,
as const)
-
Functions
- Return type annotations
- Optional and default parameters
- Rest parameters and tuples
- Overloads
voidvs.undefinedreturn types- Arrow functions vs. function declarations
-
Modules and Imports
- Import ordering
- Barrel files (
index.ts) - Re-exports
- Path aliases
- Circular dependency avoidance
-
Async and Error Handling
async/awaitvs. Promises- Typed error handling patterns
Result/Eitherpatterns- Error class conventions
- Never swallowing errors silently
-
Null and Undefined
- Nullish coalescing (
??) and optional chaining (?.) - When to allow
nullvs.undefined - Non-null assertion operator (
!) rules
- Nullish coalescing (
-
Objects and Arrays
- Immutability (
readonly,as const,Readonly<T>) - Destructuring conventions
- Spread usage rules
- Immutability (
-
Comments and Documentation
- JSDoc usage rules
- Inline comment standards
@deprecatedand@internaltags- Avoiding self-evident comments
-
File and Project Structure
- File naming and casing
- Folder organization
- Module boundaries
- Co-location rules
-
Formatting and Style
- Indentation and spacing
- Semicolons
- Quotes (single vs. double)
- Trailing commas
- Line length limits
- Prettier / ESLint configuration
-
Testing Conventions
- Type-safe test utilities
- Mocking typed dependencies
- Asserting types in tests