Evgenii Vedegisthoughts about software development

How to use TypeScript with Vue 3

Date published: August 26, 2021

Guide for Vue 3 and TypeScript. From installation to examples and advice with Composition and Options API.

Vue 3 and typescript guide

In this article:

  • how to set up TypeScript with vue 3
  • examples with options API
  • examples with composition API
  • resume

Setting up TypeScript with vue 3

Install the Vue-CLI project from npx:

npx @vue/cli create --default my-ts-project

Or create a new Vue 3 app via global npm package and choice typescript support:

npm install --global @vue/cli

vue create my-ts-project

Whatever option you choice hit the space key to choice this settings:

  1. Choose 3th version of vue
  2. Babel support
  3. And TypeScript support

Other options at your discretion

Tsconfig json for vue

When process is finish config for ts tsconfig.json will created automatically.

Mine config for work with vue.js:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": 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"
  ]
}

Defining Vue 3 Component

For start to use TypeScript inside Vue.js 3 component you need to define components with defineComponent global method:

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

  export default defineComponent({
    // code is here
  })
</script>

Vue 3 Options API with TypeScript

Let's start with option API examples and create simple interface for data object of user

First let's make interface:

interface IUser {
  login: string
  age: number
  isOnline: boolean
}

And apply for data of user:

<script lang="ts">

interface IUser {
  login: string
  age: number
  isOnline: boolean
}

import { defineComponent } from 'vue'

export default defineComponent({
  data() {
    return {
      user: {
        login: 'vedegis',
        age: 24,
        isOnline: true
      } as IUser
    }
  }
})
</script>

Computed on Options Api with TypeScript:

Here's example with Computed properties of user that we did above on Options api

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

export default defineComponent({
  // ...

  computed: {
    // setter and getter needs to be annotated
    userData: {
      get(): object {
        return this.user
      },
      set(newUser: object) {
        this.user = newUser
      }
    }
  }
})
</script>

Methods on Options Api with TypeScript:

Methods in TypeScript even options or composition api looks like normal class methods, have an optional access modifier:

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

export default defineComponent({
  public calculateNumbers(a: number, b: number): number {
    return a + b
  }
})
</script>

Vue 3 Composition API with TypeScript

Time to check how to works with TypeScript usage Composition API and Vue 3.

Here's data with user interface as we did before:

import { defineComponent, ref } from 'vue'
interface IUser {
  login: string
  age: number
  isOnline: boolean
}

setup() {
  const user = ref({} as IUser)

  return {user}
}

Methods with TypeScript on Composition api

Here's example of fetching data from api and set user:

import { defineComponent, onMounted } from 'vue'

setup() {
  // ...

  onMounted(() => getUser())

  const getPeople = () =>
    DataService.getAll()
      .then((res: ResponseData) => {
        user.value = res.data
      })
      .catch((e: Error) => console.log(e))
}

Setting up Props with TypeScript

Here's Props setup for options and composition api for TypeScript:

import { defineComponent, PropType } from "vue";

interface IUser {
  id: number;
  login: string;
  // ...
}

export default defineComponent({
  props: {
    user: {
      required: true,
      type: Object as PropType<IUser>,
    },
    storeUser: {
      required: true,
      type: Function as PropType<() => void>,
    }
  },
});
</script>

Resume

TypeScript can help prevent many potential errors as your application grows! You also don't need any additional tools to use TypeScript in Vue,js 3 because it's already comes with best support. I highly recommend use TypeScript with Vue it's pretty simple and result that you'll get will be much more than the time you spent on writing the interfaces etc :)


© Copyright 2021, Evgenii Vedegis