-
Using
letandconstinstead ofvar: In TypeScript (and modern JavaScript), it is recommended to useletandconstfor variable declarations instead of the traditionalvar.letprovides block-scoped variables, whileconstis used for declaring constants whose values should not change after declaration.Example:
typescriptlet userName = "Alice"; const MAX_LOGIN_ATTEMPTS = 5; -
Explicitly Specifying Types: One of TypeScript's core features is its static type system. When declaring variables, it is best to explicitly specify types. This not only helps catch potential errors during compilation but also improves code readability.
Example:
typescriptlet age: number = 30; let isActive: boolean = true; -
Leveraging Type Inference: When TypeScript can clearly infer the variable's type, you can omit the type declaration. Although this reduces code redundancy, it should be used cautiously to avoid misunderstandings.
Example:
typescriptlet firstName = "Bob"; // Type inferred as `string` -
Defining Complex Types with Interfaces or Type Aliases: For complex data structures, use interfaces (
interface) or type aliases (type) to define types. This enhances code reusability and clarity.Example:
typescriptinterface User { name: string; age: number; isActive: boolean; } let user: User = { name: "Charlie", age: 25, isActive: true }; -
Avoiding the
anyType: Avoid using theanytype as much as possible, as it removes the protection of type checking. If necessary, provide a comment explaining the reason.Example:
typescript// Avoid as much as possible let data: any = fetchData(); -
Reasonably Utilizing Enums: When a variable's value should be one of a specific set of values, using an enum enhances type safety and makes the code clearer.
Example:
typescriptenum Color { Red, Green, Blue } let favoriteColor: Color = Color.Green;
Following these rules helps me write safer and more maintainable TypeScript code.