Typescript: How to use it with Vue JS

TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. You can use this language for application-scale JavaScript development. Also, it can be executed on any browser, any host, and any Operating System. In this article, we will understand what is TypeScript, why do we need to use and how to use it with Vue Js.

What is TypeScript?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It is pure object-oriented with classes, interfaces and statically typed programming languages like C# or Java. You will need a compiler to compile and generate the code in the JavaScript file. Basically, TypeScript is the ES6 version of JavaScript with some additional features.

typescript logo - what is typescript -

A TypeScript code is written in a file with .ts extension and then compiled into JavaScript using the compiler. You can write the file in any code editor and the compiler needs to be installed on your platform. After the installation, the command tsc <filename>.ts compiles the TypeScript code into a plain JavaScript file.

Syntax:

12var message:string = "Welcome to Edureka!"console.log(message)

On compiling, it generates the following JavaScript code:

123//Generated by typescript 1.8.10var message = "Welcome to Edureka!";console.log(message);

Now that you have understood what is TypeScript, let’s see why do we need to use it.

Why do we use TypeScript?

There are many reasons why a JavaScript developer should consider using TypeScript. Some of them include:

  • Using new features of ECMAScript: TypeScript supports new ECMAScript standards and transpile them to ECMAScript targets of your choice. So, you can use features of ES2015 and beyond, like modules, lambda functions, classes, the spread operator, de-structuring, today.
  • Static typing: JavaScript is dynamically typed and does not know what type a variable is until it is actually instantiated at run-time. TypeScript adds type support to JavaScript.
  • Type Inference: TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. Even if you don’t explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.
  • Better IDE support: The development experience with TypeScript is a great improvement over JavaScript. There is a wide range of IDEs that have excellent support for TypeScript.
  • Strict Null Checking: Errors, like cannot read property ‘x’ of undefined, is common in JavaScript programming. You can avoid most of these kinds of errors since one cannot use a variable that is not known to the TypeScript compiler.
  • Interoperability: TypeScript is closely related to JavaScript so it has great interoperability capabilities. But some extra work is required to work with JavaScript libraries in TypeScript.

Features of TypeScript

features - what is typescript
  • Cross-Platform:  The TypeScript compiler can be installed on any Operating System such as Windows, MacOS, and Linux.
  • Object-Oriented Language: TypeScript provides features like Classes, Interfaces, and Modules. Thus, it can write object-oriented code for client-side as well as server-side development.
  • Static type-checking: TypeScript uses static typing and helps type checking at compile time. Thus, you can find errors while writing the code without running the script.
  • Optional Static Typing: TypeScript also allows optional static typing in case you are using the dynamic typing of JavaScript.
  • DOM Manipulation: You can use TypeScript to manipulate the DOM for adding or removing elements.
  • ES 6 Features: TypeScript includes most features of planned ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions, etc.

Benefits of Using TypeScript

  • TypeScript is fast, simple, easy to learn and runs on any browser or JavaScript engine.
  • It is similar to JavaScript and uses the same syntax and semantics.
  • This helps backend developers write front-end code faster.
  • You can call the TypeScript code from an existing JavaScript code. Also, it works with existing JavaScript frameworks and libraries without any issues.
  • The Definition file, with .d.ts extension, provides support for existing JavaScript libraries like Jquery, D3.js, etc. So, TypeScript code can add JavaScript libraries using type definitions to avail the benefits of type-checking, code autocompletion, and documentation in existing dynamically-typed JavaScript libraries.
  • It includes features from ES6 and ES7 that can run in ES5-level JavaScript engines.

Using TypeScript with Vue

Installation of TypeScript

On a new project

If you start a new project you can use the Vue CLI with your own settings and select Typescript in the choices.

Install TypeScript with Vue CLI

Then say yes to use class-style component syntax. We will see later why you should use this syntax.

Use vue class components in Vue CLI

On an existing project

If you add it to an existing project, you can still add TypeScript with NPM :

npm install -g typescript

Code syntax to use TypeScript in Vue

First, let’s tell our Vue compiler that Javascript will be TypeScript. In your Vue file, in the script tag, do the following :

<template>
</template>

<!--Add lang="ts" to specify it's TypeScript-->
<script lang="ts">
</script>

<style>
</style>

Then we need to modify our syntax to be TypeScript friendly.

During the installation (with Vue CLI) I suggested you use class-style component syntax. But other syntaxes exist. In Vue, there is 3 main syntax : the Options API, the Composition API, and the Class API. I suggest you use the latter. But we will see how to use TypeScript with them.

Options API

This syntax is the basic syntax of Vue. But you need to export your component differently. The usual export doesn’t have type inference enabled :

<template>
</template>

<script lang="ts">
export default {
  //No type inference
  components: {},
  data() { return {} },
  computed: {},
  created() {},
  methods: {}
}
</script>

<style>
</style>

Therefore, you will need to use Vue.extend syntax to export your Javascript :

<template>
</template>

<script>
import Vue from 'vue';

// Note the Vue.extend
export default Vue.extend({
  //Type inference
  components: {},
  data() { return {} },
  computed: {},
  created() {},
  methods: {}
})
</script>

<style>
</style>

At the beginning of my project, we were using the options API for our Vue files. But we had some issues with TypeScript and decided to use Class API. Honestly, in hindsight, I think some issues came from us not using TypeScript correctly with the options API.

Composition API

This syntax is the new syntax of Vue 3. The syntax has been build with TypeScript integration in mind. Therefore, there will be better TypeScript support with the composition API and I think you won’t have to change your syntax to use TypeScript. If you want to use this syntax in Vue 2, the composition-api package is available. Vue 3 will be released start of 2020 and is currently in (pre)-alpha. If you have time to take a look at this new syntax I suggest you to start coding with it to familiarise yourself with Vue 3.

Class API

The primary goal of introducing the Class API was to provide an alternative API that comes with better TypeScript inference support.

To use the Class API syntax, you will need to install the package vue-class-component (already installed with Vue CLI).

Then create a Vue component using the following syntax :

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  props: {
    myProp: {
      type: String
    }
  }
})
export default class HelloWorld extends Vue {
  myData: {name: string} = {name: 'test'}

  // computed are declared with get before a function
  get myComputed(): string {
    return this.myData.name
  }

  created() {}

  // methods are just functions
  myMethod(): boolean {
    return false
  }
}

You will get used to this syntax in no time!

One advantage of this syntax is that you can regroup ‘methods’ and ‘computed’ by functionality (the composition API is also built to do that).

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({})
export default class HelloWorld extends Vue {
  // Autocomplete functionality
  get computedRelatedToAutocomplete() {
    ...
  }
  methodRelatedToAutocomplete() {
    ...
  }

  // Search Functionality
  get computedRelatedToSearch() {
  ...
  }
  methodRelatedToSearch() {
  ...
  }
}

The package vue-class-component is fully supported by Vue 2.

One more improvement we can make is by using the package vue-property-decorator. This package is also installed by Vue CLI. With it, even the props will be inside the definition of the component :

import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
  // The props are defined here with the annotation @Prop()
  @Prop()
  private msg!: string;

  myData: {name: string} = {name: 'test'}

  // computed are declared with get before a function
  get myComputed(): string {
    return this.myData.name
  }

  // methods are just functions
  myMethod(): boolean {
    return false
  }
}

Drawback : The Class API is still not perfect with TypeScript. And it will be replaced by the Composition API in Vue 3. After Vue 3 is released I strongly encourage you to use the Composition API.

But currently, it’s our best solution! And changing from one notation to another is not that complicated. You can change one file at a time and still run the other files with another syntax. That is what we did to change from the options API to the class API. And even today, we still have old files with the options API syntax (that we are migrating little by little).

Actually, you can also implement TypeScript one file at the time with Vue (if you add it to an existing project). You take one of your Vue files and add the lang=”ts” inside the script tag. Then you modify your component to use the Class API and fix the potential errors TypeScript found. It’s really easy!

Want to work with web development company?

A development company is the best option if you’re planning a mid-sized or large project but don’t have your own team. To clarify, the biggest advantage of a software development company is that they can take ownership of the whole project.

If you’re considering web development services, you can explore more about us – ArrowHiTech. We are proud to be one of the most well-established outsourcing companies all around the world. In addition, with over 12 years of experience, we can provide the best software development services for your eCommerce business.

So, you can check us out now: ArrowHiTech services. Also, if you want to go through our showcase, you should visit our product page here: MageSolution or our portfolio: ArrowHiTech portfolio.

ArrowHiTech services

If you have any questions, don’t hesitate to contact us via:

  • Email: support@arrowhitech.com
  • Phone number: +84 243 7955 813.