Typescript best practices
Table of contents
Open Table of contents
Use Explicit Types
Always annotate variables, function parameters, and return types with explicit types. This helps in making your code more readable and catches potential errors early.
// Bad
function add(a, b) {
return a + b;
}
// Good
function add(a: number, b: number): number {
return a + b;
}
Enable Strict Mode
Enable strict mode in your tsconfig.json file. This includes options like strict, noImplicitAny, strictNullChecks, etc., which can catch more potential errors during development.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
Avoid Using any Type
Minimize the use of the any type as it defeats the purpose of using TypeScript. Try to provide specific types whenever possible.
Use Union Types and Enums
Utilize union types and enums to represent a finite set of values. This makes your code more readable and less error-prone.
// Union Types
type Status = 'success' | 'error';
// Enums
enum Direction {
Up,
Down,
Left,
Right
}
Interfaces Over type for Shape
Use interfaces when defining the shape of an object. Use type when you need to create union types or other utility types.
// Interface
interface Person {
name: string;
age: number;
}
// Type
type Point = {
x: number;
y: number;
};
Use Readonly and ReadonlyArray
Use readonly to create immutable properties and arrays. This helps prevent accidental modifications.
interface Config {
readonly server: string;
readonly port: number;
}
const numbers: ReadonlyArray<number> = [1, 2, 3];
Destructuring with Care
Be cautious with deep object destructuring, as it might make your code less readable. Consider destructuring only the properties you need.
// Bad
const { user: { address: { city } } } = data;
// Good
const { user } = data;
const { city } = user.address;
Use TSLint or ESLint with TSLint Plugin
Consider using TSLint or ESLint with the TSLint plugin to enforce coding standards and catch potential issues.
Modularize Your Code
Organize your code into modules and use the export and import keywords to maintain a clean and modular codebase.
Document Your Code
Add comments and use JSDoc-style comments to document your code. This is especially important for functions, explaining their purpose and expected inputs/outputs.
Test Your Code
Write tests using a testing framework like Jest. TypeScript integrates well with testing frameworks, and having a robust test suite helps catch regressions and ensures the reliability of your code.
Keep Dependencies Updated
Regularly update your TypeScript version and other dependencies to benefit from bug fixes, new features, and improved performance.