Helpful TypeScript Trick
We will see an interesting and useful type in TypeScript, which will help us know what properties we need based on having one property or another.
It's important to master these aspects of TypeScript to implement our types properly in our apps.
If we don't know this, we can end up typing things the wrong way. Many developers don't define their types well because they don't see this.
TypeScript Trick
If we want to incorporate certain properties or others based on one or more properties, we must do the following:
We assume the type CarType, where we have a property that will be common, the "price". Then we want to have different properties depending on the brand property.
If the brand is "Toyota", we want the object to have the property "isCorolla". If it is "BMW", we want it to have the property "isX6".
This way, these two objects with that type are well-defined:
On the other hand, if we put the type with "Toyota" the property "isX6" and vice versa, we see how the TypeScript errors appear in both cases:
Conclusion
This TypeScript trick is helpful when we have a specific use case where we need determined properties depending on others and want to type it in the same type. I hope that's helpful!
Here, I share a helpful video by Josh that also talks about this topic. I highly recommend it:
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!