Semicolons in TypeScript
October 30, 2023
Basic Usage in Statements
;) to separate statements on the same line.
While ASI can make your life easier, it can also introduce subtle bugs. Therefore, many developers and style guides suggest always including semicolons explicitly for clarity.
In Interfaces and Type Aliases
When you're defining TypeScript interfaces or type aliases, properties and methods within interfaces should be separated with semicolons.
However, if you come from a background of using Prettier or certain other linting tools, you might be used to comma-separated properties. While this is technically valid in TypeScript, it's not the conventional style and can lead to inconsistency.
In Enum Declarations
For enum declarations, members are separated by commas, not semicolons.
In class definitions, method definitions don't require a trailing semicolon, but property declarations do.
Tips and Best Practices
Consistency is Key: Whether you choose to use semicolons or rely on ASI, it's important to be consistent throughout your project. This makes the codebase easier to read and maintain.
Consider Using a Linter: Tools like TSLint or ESLint (with TypeScript support) can help enforce consistent semicolon usage across your project.
Beware of Edge Cases with ASI: There are certain scenarios where ASI might not behave as expected. For example:
In the code above, ASI will insert a semicolon after
return, potentially causing unexpected behavior. Always be cautious and understand the implications of omitting semicolons.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript