TypeScript with Vue
Building type-safe Vue applications
🚀 What is TypeScript with Vue?
TypeScript enhances Vue development by adding static typing, better IDE support, and early error detection. It makes your Vue components more reliable and easier to maintain with type safety.
// Simple Vue component with TypeScript
import { defineComponent } from 'vue'
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String
}
})
Key Features
Type Safety
Catch errors before runtime
interface User {
name: string
age: number
}
Better Tooling
Enhanced autocomplete and IntelliSense
const user: User = {
name: 'John',
age: 25
}
Props Typing
Define component props with types
props: {
count: Number,
title: String
}
Composition API
Full TypeScript support with setup
<script setup lang="ts">
import { ref } from 'vue'
</script>
🔹 Basic Vue Component with TypeScript
Create a simple counter component using TypeScript:
<script setup lang="ts">
import { ref } from 'vue'
// Define typed reactive state
const count = ref<number>(0)
// Typed function
const increment = (): void => {
count.value++
}
</script>
<template>
<div>
<h2>Count: {{ count }}</h2>
<button @click="increment">Increment</button>
</div>
</template>
Output:
Count: 0
🔹 Defining Props with TypeScript
Use interfaces to define component props:
<script setup lang="ts">
// Define props interface
interface Props {
title: string
count?: number // Optional prop
isActive: boolean
}
// Use defineProps with type
const props = defineProps<Props>()
</script>
<template>
<div>
<h3>{{ props.title }}</h3>
<p>Count: {{ props.count || 0 }}</p>
<p>Status: {{ props.isActive ? 'Active' : 'Inactive' }}</p>
</div>
</template>
🔹 Typed Computed Properties
Create computed properties with type inference:
<script setup lang="ts">
import { ref, computed } from 'vue'
const firstName = ref<string>('John')
const lastName = ref<string>('Doe')
// Computed with automatic type inference
const fullName = computed<string>(() => {
return `${firstName.value} ${lastName.value}`
})
</script>
<template>
<p>Full Name: {{ fullName }}</p>
</template>
🔹 Emitting Events with Types
Define typed events for component communication:
<script setup lang="ts">
// Define emit types
const emit = defineEmits<{
update: [value: string]
delete: [id: number]
submit: []
}>()
// Emit typed events
const handleUpdate = () => {
emit('update', 'new value')
}
const handleDelete = () => {
emit('delete', 123)
}
</script>