Vue 2’s TypeScript support was… okay, but awkward. It often required class-based components or clunky decorators. Vue 3 was written in TypeScript from the ground up, and the integration is now seamless, especially with the Composition API.
Defining Props
In <script setup lang="ts">, you can use pure TypeScript interfaces to define props.
<script setup lang="ts">
interface Props {
title: string
count?: number
items: string[]
}
// withDefaults lets you provide default values
const props = withDefaults(defineProps<Props>(), {
count: 0,
items: () => []
})
</script>
Typing Emits
Strictly typed events ensure you pass the right payload.
const emit = defineEmits<{
(e: 'update', value: string): void
(e: 'delete', id: number): void
}>()
emit('update', 'new value') // OK
emit('update', 123) // Type Error!
Typing Refs
import { ref } from 'vue'
// Inferred
const count = ref(0) // Ref<number>
// Explicit
const user = ref<User | null>(null)
// Generic components also supported!
<script setup lang="ts" generic="T">
defineProps<{
items: T[]
}>
</script>
Verdict
If you hesitated to use TypeScript with Vue before, try it now with Vue 3. The tooling (Volar extension for VS Code) provides incredible type inference in templates. It’s a massive productivity boost.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.