Start using Typescript in Vue. The easy way.
Start to use a new technology, new paradigm, new framework or anything could be hard and challenging, this is why is important start integrating new technologies avoiding friction with previous one. Today I’ll try to show you the easiest way to start using Typescript in your Vue projects.
Before start, you should know Typescript using benefits. You have thousands blog’s post talking about that:
I assume you are using
vue-cli. You must be sure you are using version 4.0.0+
First step is add Typescript using
vue add typescript
Vue cli starts to add typescript package and necessary dependencies. Also create and update configuration files like
tsconfig.json, It needs ask you some questions to configure properly.
Let view each question in detail and the “correct” answer.
? Use class-style component syntax? (Y/n)
If you want start to use class-style component syntax you should answer “yes“. You can answer “no” and you can not use it, but anything else changes.
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n)
“Yes”. You were probably already using it.
The next two questions are the most important
? Convert all .js files to .ts? (Y/n)
You must answer “No“ to avoid Vue cli rename all your files to
.ts. If you do that you will have to refactor all your project files to Typescript
? Allow .js files to be compiled? (y/N)
You must answer “Yes“. It’s the same as, in
tsconfig.json, set the value
true. If you don’t anwser “yes” you will receive a lot of error messages, because the typescript transpiler tries to transpilate
No step 2. You just added Typescript support to your project and everything should work fine as usual.
To write a Vue compoment using Typescript you need to set the scripting language using the attribute
lang in the script tag.
Also, as Typescript needs to infer types, you must define your components with
Vue.extend (I prefer second one)
Then our component look like:
Done! You have your first Typescript Vue component.
The point is you can start using Typescript and keep your previous code. You don’t need to rewrite all components, or you can do step by step.
I recommend you to read Vue documentation about Typescript support
In future blog posts I show how use multiple mixins in Typescript and other tips about typescript