The joy of building Vue apps in Typescript — Part 1: Vue Class Components
It is more than just a bit of type-safety and autocomplete here and there
So I just discovered https://codesandbox.io/ and I figured it would be a great medium to show some samples and embed it in a medium article. There are codesandbox examples in this article. These are extremely live and reactive. You can edit the code inside them, and/or interact with the generated preview on the right.
I have been meaning to write an article on the beauty of Vue apps written in Typescript for quite a while. I have personally invested a lot of my mindshare into this, and have published over 5 (2 of them very popular) Vue and Vuex related libraries which makes Typescript development all the more easier
Let us start of with a simple Vue.js project that has a component with a counter in it.
Let us create another counter like this, but now write the code for that in Typescript. Before that we’ll install vue-class-component
library. It is an officially maintained Vue library that helps us write class-style components. Also we’ll make sure that the experimentalDecorators
flag is turned on in our tsconfig.json
As you’ll see now we are exporting not an object, but a class that extends the Vue class.
If you use @vue/cli
and generate the template while keeping Typescript enabled, you’d have the required ts-loader
module and tsconfig.json
config already generated for you, so you can straightaway start writing <script lang="ts">
blocks.
Let us see how Typescript uses proxy getters to make Vue’s computed pattern work. First, quick example in Javascript. An ‘isOdd’ computed property is used to find if the number is odd or even. (Click on the INCREMENT button and see what happens).
Now the same thing in Typescript — using the get
accessor
What I like when using Typescript is that when we write something like this.count
we actually mean the “count” variable inside this. Unlike the Javascript case where the data is actually inside component.data.count
and the function is component.methods.increment()
and it doesn’t actually make sense that the this inside a method would point to the data too.