Good practices
Strict Typing
Strict typing in TypeScript is a fundamental feature that helps detect and prevent type errors during the development phase. This helps improve the quality and robustness of the code, as well as facilitate maintenance and refactoring.
Variable Typing
Basic Types
Object Typing
Function Typing
Parameters and Return Type
Interfaces and Custom Types
Interfaces
Custom Types
Class Typing
General Conventions
Magic String
Avoid "Magic Strings": Do not use literal strings directly in the code, especially when referring to known constants. Instead, define constants or enumerations to represent these values.
Static Typing
Take full advantage of TypeScript's type system to avoid common errors and improve code clarity.
Avoid Any
Avoid using any as much as possible, as it removes type checking and can introduce hard-to-detect errors.
Descriptive Data Type Naming
Use descriptive names for data types and avoid ambiguous abbreviations.
Project Structure
Organize Files Logically
Group related files in logical folders to facilitate code navigation and maintenance.
Separate Data Types in Definition Files
Place data type definitions in separate files to improve reusability and clarity.
Use Modules and Namespaces Consistently
Use modules and namespaces consistently according to the project structure and code organization needs.
Documentation
Include Descriptive Comments
Document functions, classes, and types with descriptive comments to facilitate code understanding.
Use JSDoc to Document Functions and Methods (if necessary and the method is very complex)
Use JSDoc to document functions and methods, including descriptions, parameters, and return values.
Tools and Configuration
Configure tsconfig.json
Use a well-configured tsconfig.json file to set compilation options and maintain consistency throughout the project.
Use Linter
Set up a linter (such as ESLint) with specific rules for TypeScript to keep the code clean and consistent, using Sonarlint.
Integrate Unit Tests
Integrate unit tests to ensure code quality and facilitate long-term maintenance.
Conclusions
Strict typing in TypeScript provides significant benefits, such as early type error detection, improved code readability, and better automatic documentation. By consistently applying strict typing, code quality and maintainability can be improved over time.
Last updated