When it comes to naming types in TypeScript, opinions on the best practices can vary. What works for one developer might not resonate with another. It’s essential to note that these recommendations are not a silver bullet, but rather a collection of opinions and practices aimed at fostering code clarity and maintainability. Let’s explore these suggestions and consider how they might fit into your own coding style and project requirements. Remember, while these guidelines offer valuable insights, the ultimate decision lies in finding an approach that aligns with your team’s preferences and the specific needs of your TypeScript project.
Table of contents
Open Table of contents
1. Never Pluralize
The first rule is to never pluralize type names. Even when dealing with a union type representing multiple instances, the convention is to use the singular form. For instance, if you have a union type Roles
containing user, admin, and superuser, consider naming it Role
instead.
type Role = "user" | "admin" | "superuser";
function goToRoot(role: Role) {
// Function logic here
}
// Instead of Role array
const roleArray: Role[] = ["user", "admin", "superuser"];
2. Use Different Case for Types and Variables
Using different casing for types and variables is a smart move to dodge syntax highlighting mix-ups. Stick to Pascal case for types and lowercase for variables – it’s the common convention. This keeps things clear and makes sure your syntax highlighting is on point.
type Role = "user" | "admin" | "superuser";
// Good: Different casing
function goToRoot(role: Role) {
// Function logic here
}
// Avoid: Same casing
const Root = "user";
3. Type Parameters: Prefix with ‘T’
When working with generic type parameters, it’s recommended to prefix them with ‘T’ for clarity. For single-value types, using a single letter like ‘T’ is fine. When dealing with multiple values, go for ‘T’ followed by a descriptive name, like ‘TData’.
type Response<TData, TError> = {
data: TData;
error: TError;
};
// Good: Prefix with 'T'
const result: Response<string, Error> = {
data: "Success",
error: new Error("Something went wrong"),
};
4. Unnecessary Prefixes
Avoid unnecessary prefixes like ‘I’ for interfaces and ‘T’ for types. For instance, instead of using TUser
and IOrganization
, consider directly using User
and Organization
.
This practice reduces redundancy and makes the code more concise and maintainable.
// Avoid unnecessary prefixes
interface User {
// Interface properties
}
type Organization = {
// Type properties
};
Conclusion
In summary, following these naming conventions can significantly improve the readability and maintainability of your TypeScript code. Remember to keep things singular, use different case for types and variables, prefix type parameters with ‘T,’ and avoid unnecessary prefixes for cleaner and more consistent code.