Learning TypeScript 07 — Augmenting types
One of the biggest problems in TypeScript are the typings, luckily libraries like Vue and bring them as standard, in addition to including some decorators to facilitate the work .
Although we have a small problem when we decide to use third-party plugins or our own plugins, TypeScript does not recognize the plugin as property of one of our components, let’s see an example:
I have a project made with Vue where I installed the ‘Vue Analytics’ plugin to integrate with Google Analytics, but this plugin is typed and when I decide to use it in my component my editor shows me an error.
Quick solution
We have all been in a hurry to solve something and instead of investigating, we decided temporarily (If … temporarily) to fix this quickly, if we are in one of those cases we will surely obtain a solution such as this, which consists in declaring a property in the same component so that it exists in TypeScript and in JavaScript.
Perfect this works, but it is not enough. We can think of creating a Base component from which the rest of the components extend so that this is reusable. Although still not the best solution. It would not be a bad decision to create a Base interface or an interface for each plugin that we will need.
Solution using ‘augmenting types’
The same documentation of Vue (If it is that sometimes looking for 5 minutes you find the correct solution …)proposes us to use the ‘module augmentation’ to solve this in a much cleaner way.
First of all we created a folder typings in the root of our project (TypeScript should include it automatically next to the rest of typings) and inside a file where we are going to declare the plugins extending the typings of Vue, in my case I have called it vue.d.ts
And within this file we added the code that gave us the documentation, adding the properties we need.
Bonus, using less ‘any’
Remember that it is always a good practice to try to use the minimum type ‘any’ so we can create interfaces or declare types with the desired structure and add them.
Also, sometimes the plugins already come with their types so you can add them if you consider it necessary.
You can find more info about this article in the official guide.
And info about why I’m doing this articles about TypeScript.
Let’s continue with the next chapter: Testing Workshop.
And remember, feedback is welcome 🤙.