Learning TypeScript 07 — Augmenting types
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.
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’
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 🤙.