Hey everyone! This post is meant to help you improve how your project's data types are connected, making them more reliable and easier to understand.
TLDR for you folks in a hurry: avoid repeating types and consts that refer to the same thing and try to give them suggestive names (even if they are a simple string or a number). This will make it easier for you to identify, modify, or remove your code later.
Imagine you are developing an e-commerce website, and you have defined the product's type as:
export type ProductType = { id: string; name: string; price: number; };
On a project of this kind, you can easily find multiple ways where one might refer to a product's id, from simple functions:
To more advanced situations, such as saving a product's data in a state store, or passing props to other components in JS Frameworks
Now let's address the issue(s) with this approach:
To address issue one, you could use Template Literals Types, which would make the new product id's type: ${string}-${string}-${string}-${string}. Repeating this across multiple files would now be annoying, so one could either:
type ProductIdType = `${string}-${string}-${string}-${string}`
If needed, you could also create and refer to different types for each string, or refer to others you created previously. Finally you would use the new type as such:
(productId : ProductIdType) => {...}
(productId : ProductType['id']) => {...}
Both these approaches would solve issue two: wherever you'd find ProductIdType or ProductType['id'], you'd know that you were dealing with a product's id, and knew that you should replace it.
The first solution might seem friendlier, but you would now have a bi-parted structure, where you have one type for the product and another for the id, which can be used independently. Here's an example representation of said structure:
This is no doubt a smaller issue, but if you change/delete the id entry of the ProductType, that change wouldn't be reflected in your whole project.
The last approach, however, is the one I usually follow, because it increases your data's coupling (by lack of a better word). All your references to the product's data now point directly to the ProductType:
I'm not saying you should always create types for all your data. Whenever I see myself repeating references to the same data's type, I usually opt to access the original one, as in the second approach.
Bonus tip 1: You can apply the same logic for consts: If you see yourself repeating the same magic number or string in multiple places, it's best to give it a proper designation and use it.
Bonus tip 2: Use Pick, Omit and Exclude and other Utility Types if you want to select/exclude more than one entry of a type instead of repeating them.
That's all! I hope you liked my post. Feel free to leave your feedback on this topic.
The above is the detailed content of Improving Coupling in your Project. For more information, please follow other related articles on the PHP Chinese website!