0
0
Vueframework~5 mins

Setting up TypeScript in Vue project

Choose your learning style9 modes available
Introduction

TypeScript helps catch mistakes early and makes your code easier to understand. Setting it up in a Vue project lets you write safer and clearer code.

You want to avoid bugs by checking your code before running it.
You want better code suggestions and auto-completion in your editor.
You plan to build a bigger app that needs clear structure.
You want to use modern JavaScript features with type safety.
You want to work with other developers who use TypeScript.
Syntax
Vue
npm create vue@latest
# Choose 'TypeScript' when prompted

# Or manually add TypeScript to an existing project:
npm install -D typescript @vue/tsconfig

# Rename .js files to .ts or .vue with <script lang="ts">

# Add a tsconfig.json file for TypeScript settings

Use npm create vue@latest to start a new Vue project with TypeScript easily.

In Vue files, add lang="ts" inside the <script> tag to write TypeScript.

Examples
This creates a new Vue project with TypeScript ready to use.
Vue
npm create vue@latest
# Select 'TypeScript' option during setup
Use lang="ts" in Vue components to write TypeScript code.
Vue
<script lang="ts" setup>
import { ref } from 'vue'
const count = ref(0)
</script>
This file tells TypeScript how to check your Vue project code.
Vue
{
  "extends": "@vue/tsconfig/tsconfig.json",
  "compilerOptions": {
    "strict": true
  }
}
Sample Program

This Vue component uses TypeScript to define a message variable with a string type. The button updates the message when clicked.

Vue
<script lang="ts" setup>
import { ref } from 'vue'

const message = ref<string>('Hello TypeScript in Vue!')

function updateMessage(newMsg: string) {
  message.value = newMsg
}
</script>

<template>
  <div>
    <p>{{ message }}</p>
    <button @click="updateMessage('You clicked the button!')">Click me</button>
  </div>
</template>
OutputSuccess
Important Notes

Remember to rename your Vue script tags to lang="ts" to enable TypeScript.

Use ref<type>() to tell Vue what type your reactive data holds.

Check your editor supports Vue and TypeScript for best experience.

Summary

TypeScript helps catch errors and improve code clarity in Vue projects.

Use npm create vue@latest and pick TypeScript to start easily.

Add lang="ts" in Vue scripts and create a tsconfig.json file.