0
0
Vueframework~5 mins

Why TypeScript matters in Vue

Choose your learning style9 modes available
Introduction

TypeScript helps catch mistakes early and makes your Vue code easier to understand and maintain.

When building a large Vue app with many components.
When working in a team to keep code consistent.
When you want better code suggestions and error checking in your editor.
When you want to avoid bugs caused by wrong data types.
When you want to write clearer and safer Vue components.
Syntax
Vue
<script lang="ts" setup>
import { ref } from 'vue'

const count = ref<number>(0)

function increment() {
  count.value++
}
</script>
Use lang="ts" in the script tag to enable TypeScript in Vue components.
TypeScript types like number help Vue know what kind of data you expect.
Examples
Declare a string variable with a type to avoid mistakes like assigning numbers by accident.
Vue
<script lang="ts" setup>
const message: string = 'Hello Vue with TypeScript!'
</script>
Use ref with a type to track reactive boolean state safely.
Vue
<script lang="ts" setup>
import { ref } from 'vue'
const isVisible = ref<boolean>(true)
</script>
Define an interface to describe complex data shapes and use it with ref.
Vue
<script lang="ts" setup>
import { ref } from 'vue'
interface User {
  name: string
  age: number
}

const user = ref<User>({ name: 'Alice', age: 30 })
</script>
Sample Program

This Vue component uses TypeScript to keep track of a number count. The count starts at zero and increases when you click the button. TypeScript ensures count is always a number.

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

const count = ref<number>(0)

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>
OutputSuccess
Important Notes

TypeScript works well with Vue's Composition API and <script setup> syntax.

Using TypeScript can slow down initial setup but helps prevent bugs later.

Editors like VS Code give better help when TypeScript is used.

Summary

TypeScript helps catch errors before running your Vue app.

It makes your code easier to read and maintain.

TypeScript works smoothly with Vue's modern features.