TypeScript + Vue3 Practical Tutorial

Vue 3 has excellent support for TypeScript. This tutorial introduces development practices for Vue 3 + TypeScript.

Vue 3's Composition API and TypeScript's type system combine perfectly, making code safer and easier to maintain.

View the Vue3 tutorial:https://www.example.com/vue3/vue3-tutorial.html


SVG diagram: Vue 3 + TypeScript development Background Title Vue 3 + TypeScript type support Vue 3 components Vue 3 components defineComponent() PropType<User> emits: ['edit', 'delete'] Composition API Composition API ref<T>(initial) computed<T>(() => {}) reactive<T>(obj) Type definitions Type definitions interface User { id: number name: string } Lower section: Advantages Advantages of Vue 3 + TypeScript Advantage 1 Complete type inference Advantage 2 Props type checking Advantage 3 Emits event types Arrow marker

Why use TypeScript in Vue 3

Vue 3 fully embraced TypeScript from the very beginning of its design, providing excellent type support.

The functional style of the Composition API works perfectly with the TypeScript type system: ref supports generics, computed has type inference, and props have complete type checking.

Using TypeScript gives type protection to Vue component props, events, and reactive data.

Vue 3 natively supports:Vue 3's source code is written in TypeScript, providing seamless integration with TypeScript.


Create Project

Use Vite to create a Vue 3 project with TypeScript support.

Initialization

# Create Vue with Vite3 +TypeScript project (recommended)
npm create vite@latest my-vue-app -- --template vue-ts

# Enter the project directory
cd my-vue-app

# Install dependencies
npm install

Recommendation:Vite is the official recommended build tool for Vue. When creating a project, simply select the vue-ts template.


Component Types

Use defineComponent and PropType to define component and Props types.

src/components/UserCard.vue

<template>
  <div class="user-card">
    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>
    <button @click="handleEdit">Edit</button>
  </div>
</template>

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

// Define a user type interface
interface User {
  id: number
  name: string
  email: string
}

export default defineComponent({
  name: 'UserCard',
  // Props definition
  props: {
    // Use PropType for type declaration
    user: {
      type: Object as PropType<User>,
      required: true
    }
  },
  // Declare events emitted by the component
  emits: ['edit'],
  setup(props, { emit }) {
    // Handle edit click
    const handleEdit = () => {
      emit('edit', props.user)
    }

    return { handleEdit }
  }
})
</script>

Result:

UserCard 组件渲染成功

PropType:When the props type is a complex object, you need to use PropType for type assertion.


Composition API Types

When using reactive APIs such as ref and computed, TypeScript provides complete type support.

src/components/Counter.vue

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Multiply: {{ doubled }}</p>
    <button @click="increment">+1</button>
    <button @click="decrement">-1</button>
  </div>
</template>

<script lang="ts">
import { ref, computed } from 'vue'

export default {
  setup() {
    // ref: define reactive data, specify the type with generics
    const count = ref<number>(0)

    // computed: computed property, automatically infers the return type
    const doubled = computed(() => count.value * 2)

    // Define methods
    const increment = () => {
      count.value++
    }

    const decrement = () => {
      count.value--
    }

    return { count, doubled, increment, decrement }
  }
}
</script>

Result:

Counter 组件渲染成功

Type inference:Vue 3's Composition API automatically infers types based on the initial value; for complex types, you can explicitly specify generics.


Interface Definitions

Centralize the project's type interfaces in the types directory.

src/types/index.ts

// User type definition
export interface User {
  id: number       // User ID
  name: string    // Username
  email: string   // Email
  avatar?: string // Avatar (optional)
}

// Data transfer object for creating a user
export interface CreateUserDTO {
  name: string    // Username
  email: string  // Email
  password: string // Password
}

// Generic API response type
export interface ApiResponse<T> {
  success: boolean  // Whether successful
  data?: T         // Data on success
  error?: string   // Error message on failure
}

Centralized type management:Put type definitions in the types directory for easy reuse across multiple components.


Notes

  • defineComponent:Provides complete type inference
  • PropType:Complex Props types need to use
  • ref generic:Explicitly specify complex types
  • emits:Declare event types

Best practices:Vue 3 recommends using Composition API + TypeScript for the best development experience.


Summary

Vue 3 and TypeScript combine perfectly.

  • defineComponent:Get complete type inference
  • PropType:Provide type safety for props
  • ref:Specify reactive types with generic parameters
  • computed:Automatically infer computed property types

Suggestions:TypeScript is strongly recommended for Vue 3 projects, especially in large applications.

Other extensions