Using Typescript in your Vue app

Arnav Gupta
Coding Blocks
Published in
3 min readJul 1, 2017
Image result for typesript vuejs

I am a Java convert, in the Javascript world, and ever since I have seen Typescript, I have been in love with it. It brings all the safety features of a strong-static-typed language like Java into Javascript, but is incremental.

Typescript is a superset of Javascript, which means you can start using Typescript with simply renaming yourfile.js to yourfile.ts and all the existing code in it is still valid. Now we can start incrementally turning things into classes, and assigning types to arguments, and lo and behold, soon you’ll have a reasonably type-safe code base.

TL;DR; This article is an expanded description of the following commit.

When I started using Vue, the first thing I wanted to figure out was how to use Typescript here. Two very good resources — one by Vue and one by Typescript are of a lot of help, but won’t get to the end of the road. The Vue article does not tell you about the changes we need in webpack. The Microsoft repo needs changes in Vue core.

So let us explore who we can start adding TS support to Vue. (All this is done and saved on this repo . You an use the commit history as a reference to the steps mentioned here) Start with installing the dependencies —

yarn add typescript ts-loader

Then, we need to add a tsconfig.jsonfile.

Next, we need to add ts-loaderin our webpack config.

Remember to add it right at the top of the rules, before other rules.

Also add ts to resolved extensions —

extensions: ['.js', '.vue', '.json', '.ts'],

To ensure that .vue components are treated as moduels, we need to do the following in the vue config file as well. So we need to add the esModuleflag to it.

One of the gotchas of using Typescript in Vue is that the entry point HAS TO BE in typescript. Which means, main.js must become main.ts

Basically just renaming should work, as ts is superset of js, but it will not understand component types. We can work that around using render functions. Below is the new main.ts

And finally we need to add a tiny shim to make sure tsc understands that all .vue modules are extended from the Vue class. Add this as vue.d.ts to the /src/folder.

Now you can write any code you want in ts. For .vue components, to write script in Typescript, you need to use the script tag like this —

<script lang='ts'>
//You Typescript code guess here
</script>

Obligatory shameless self-plug :
I am one of the co-founders of Coding Blocks — A Software Programming bootcamp, based out of New Delhi, India. Among other things, we teach Full Stack Web Development using NodeJS, via both classroom programmes, as well as online classes. You can follow our Medium to find more articles on Android and Web development.

--

--

Arnav Gupta
Coding Blocks

Swimmer, Coder, Poet, Engineer, Entrepreneur. Co founder of Coding Blocks. Mobile Platform at Zomato