Table of contents
1.
Introduction
2.
Prerequisites
3.
IDE Support
4.
Setting Up Vue Project
5.
Configuring the TypeScript Compiler
6.
Using the defineComponent()
6.1.
Usage in Single-File Components
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

TypeScript Support

Author Parth Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

TypeScript is a programming language that builds on Javascript and was developed by Microsoft. Typescript can detect many common errors via static analysis at build time. The end goal is to reduce the chances of a runtime error in production and allow the developer to refactor code in large-scale applications. 
Interestingly, all the official Vue.js packages have out-of-the-box support for type declarations. However, Why should TypeScript be used with Vue.js? 
Well, TypeScript provides various advantages while coding in Vue.js such as:

  • The code becomes more readable.
  • The developer receives an overall better-debugging experience.
  • IDE(Integrated Development Environment) support for detecting common errors.

Prerequisites

This blog focuses on using TypeScript with Vue.js therefore:

  • Node.js must be installed in the system.
  • Basic Knowledge about Vue.js and setting up a Vue project is required.
  • Vue CLI must be installed globally.
  • Basic Knowledge about Typescript and its conventions is a must.

This blog uses node version v14.17.3,npm version 6.14.13, and vue/cli version 5.0.1.

IDE Support

Visual Studio Code works for Typescript based projects. Therefore, this tutorial will use Visual Studio Code for its excellent out-of-the-box Typescript support.
We also require two extremely beneficial extensions to provide a better experience.

  • Volar: Provides support inside Vue SFC's
     

  • TypeScript Vue Plugin: Provides type support in TS files for .vue imports.
     

Setting Up Vue Project

Let us begin by creating a new vue project using the following command inside the command prompt.

vue create typescript-with-vue

After pressing enter, we get a prompt from the Vue CLI.

 

Note: These parameters can vary depending on the version of Vue CLI

Using the arrow down key, we have to navigate the Manually select features option and press Enter.
As we press Enter, we are again greeted with many options.

These features can be toggled on or off by using the Space Key.
Now, using the arrow keys, we navigate to the TypeScript option, press Space, and then hit Enter.
Note: If you want to add TypeScript to an old Vue.js project, input the following command.

vue add Typescript

Finally, we press Enter on the Version 3.x option to complete the manual selection process.
Note: After the version selection prompt, keep pressing Enter to select the default values if more parameters are given.
After a brief moment, the Vue app is finally generated.
Type the following code to get into the main application directory.

cd typescript-with-vue
npm run serve

Configuring the TypeScript Compiler

Inside the project directory, there is a file called tsconfig.json. The tsconfig.json files contain many options that can be toggled on or off to configure Typescripts support as per a development team's requirements.
By default, this is what the tsconfig.json looks like:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}


In our case, only three options are required to be turned on to experience the maximum benefit of TypeScript in Vue.js.
These options are:
noImplicitAny: Throws an error in case an argument, const, let, or var does not have a type defined.
noImplicitThis: Throws an error with this keyword.
noImplicitReturns: Throws an error in case a function does not return a value.
Finally, this is what our tsconfig.json file looks like:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Using the defineComponent()

We need to use defineComponent() to define components as it enables TypeScript to understand the types inside the component options properly.

import { defineComponent } from 'vue'
export default defineComponent({
  // type inference enabled
  props: {
    name_first: String,
    message: { type: String, required: true }
  },
  data() {
    return {
      count: 1
    }
  },
  mounted() {
    this.name_first // type: string | undefined
    this.message // type: string
    this.count // type: number
  }
})
You can also try this code with Online Javascript Compiler
Run Code

Usage in Single-File Components

TypeScript can be used in a Single-File Component by adding the lang="ts" attribute inside the <script> tags. When the lang="ts" is present, all the template expressions also receive strict type checking.

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  data() {
    return {
      count: 1
    }
  }
})
</script>

<template>
  <!-- type checking and auto-completion enabled -->
  {{ count.toFixed(2) }}
</template>

lang="ts" can also be paired with <script setup>:
<script setup lang="ts">
// TypeScript enabled
import { ref } from 'vue'
const count = ref(1)
</script>
<template>
  <!-- type checking and auto-completion enabled -->
  {{ count.toFixed(2) }}
</template>
You can also try this code with Online Javascript Compiler
Run Code

FAQs

  1. Can I use Vue with TypeScript?
    As Vue.js officially supports TypeScript, It is possible to create a Vue-based project that uses TypeScript.Also, some third-party packages will be required to provide additional TypeScript support for an optimum experience.
     
  2. What are the advantages of using TypeScript in Vue?
    Well, TypeScript provides various advantages while coding in Vue.js such as:
    The code becomes more readable.
    The developer receives an overall better-debugging experience.
    IDE(Integrated Development Environment) support for detecting common errors.
     
  3. How do I use TypeScript with Vue single-file components?
    To use TypeScript with Vue single-file component, you need to add a lang attribute inside the script tag. The value of the attribute should be ts. 
     
  4. How to install Vue CLI?
    To install Vue CLI, Node.js must be installed inside the system. After that, head over to the command prompt and type npm install -g @vue/cli to install Vue CLI globally in the system.
     
  5. What are the prerequisites of using TypeScript in Vue.js?
    To use TypeScript in Vue.js:
    Node.js must be installed in the system.
    Basic Knowledge about Vue.js and setting up a Vue project is required.
    Vue CLI must be installed globally.
    Basic Knowledge about Typescript and its conventions is a must.

Key Takeaways

In this article, we learned about the TypeScript support inside Vue.js.We learned how TypeScript can be added inside a Vue.js project and what advantages TypeScript provides. However, this isn't enough, as there is always much more to explore and learn about this vast field of Web Development. To know more about Vue.js and its intricacies, check out the articles on Vue.js or enroll in our highly curated Web Development course.

Recommended Readings:

Live masterclass