前言

前三篇我们已经把 Vite + Vue3 + Pinia 这套骨架搭起来了,但还有一层”安全网”没说透——TypeScript 的类型。很多人写 Vue3 + TS 时其实只是”用了 TS 的语法”,并没有真正享受类型带来的好处:props 类型写 any、emit 用 string、provide/inject 一律 unknown、泛型组件干脆不会写。

本文聚焦 Vue3 + TS 的类型进阶,把这些场景的类型写法一次讲清。读完你写出来的组件会自带完整类型提示,IDE 跳转、重构、拼写错误都能被编译器挡掉。

一、defineProps:基于类型的声明

推荐:泛型写法

1
2
3
4
5
6
7
8
9
10
11
<script setup lang="ts">
interface Props {
title: string
count?: number // 可选
size?: 'sm' | 'md' | 'lg' // 字面量联合
list: string[]
userInfo?: User // 引用业务类型
}

const props = defineProps<Props>()
</script>

特性:

  • 类型从泛型参数推导,IDE 跳转顺畅。
  • 支持联合、可选、引用外部 interface。
  • 编译期会生成运行时声明(基于 PropType),开发与生产都有类型校验。

默认值:withDefaults

TS 泛型写法下,default 不能写在对象里,要用 withDefaults:

1
2
3
4
5
6
7
8
9
10
11
interface Props {
title: string
size?: 'sm' | 'md' | 'lg'
count?: number
}

const props = withDefaults(defineProps<Props>(), {
title: '默认标题',
size: 'md',
count: 0,
})

注意:必填属性不能给默认值,可选属性给默认值后类型推断为非可选。

只读 props

1
2
const props = defineProps<Props>()
props.title = '改值' // ❌ 编译报错:readonly

要”派生”新值请用 computed,不要直接改 props。

二、defineEmits:事件签名

元组写法

1
2
3
4
5
6
7
<script setup lang="ts">
const emit = defineEmits<{
(e: 'update', value: string): void
(e: 'select', id: number, name: string): void
(e: 'success'): void
}>()
</script>

类型字面量写法(推荐)

1
2
3
4
5
const emit = defineEmits<{
update: [value: string]
select: [id: number, name: string]
success: []
}>()

调用时类型安全:

1
2
3
4
emit('update', 'xxx')           // ✅
emit('update', 123) // ❌ 参数类型不对
emit('select', 1, 'Tom') // ✅
emit('select', 1) // ❌ 缺参

父组件模板里使用:

1
<Child @update="onUpdate" @select="onSelect" />

@update 的回调参数会被推导为 string,IDE 自动补全参数名。

三、defineModel:双向绑定简化

Vue3.4+ 引入 defineModel,替代了繁琐的 props + emit 双向绑定写法。

旧写法

1
2
3
4
5
6
7
const props = defineProps<{ modelValue: string }>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()

// 改值
const input = (e: Event) => {
emit('update:modelValue', (e.target as HTMLInputElement).value)
}

新写法:defineModel

1
2
3
4
5
6
7
<script setup lang="ts">
const model = defineModel<string>()

function input(e: Event) {
model.value = (e.target as HTMLInputElement).value
}
</script>

父组件:

1
<Child v-model="text" />

defineModel 返回的 model 是个 ref,.value 读写就是双向同步。

多 model 与修饰符

1
2
3
4
5
6
7
8
9
10
const visible = defineModel<boolean>('visible')
const title = defineModel<string>('title', { default: '标题' })

// 修饰符
const search = defineModel<string>({
default: '',
set(value) {
return value.trim()
},
})

父组件:

1
<Dialog v-model:visible="open" v-model:title="title" />

注意:defineModel 需要 Vue 3.4+,老项目要 v-model + modelValue 老写法。

四、provide / inject:类型安全注入

裸 inject('xxx') 默认是 unknown,类型完全丢失。用 InjectionKey 可以让注入带上类型。

定义 Key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/composables/useTheme.ts
import type { InjectionKey, Ref } from 'vue'
import { ref, provide, inject } from 'vue'

export interface ThemeContext {
isDark: Ref<boolean>
toggle: () => void
}

export const ThemeKey: InjectionKey<ThemeContext> = Symbol('theme')

export function provideTheme() {
const isDark = ref(false)
const toggle = () => { isDark.value = !isDark.value }
provide(ThemeKey, { isDark, toggle })
}

export function useTheme() {
const ctx = inject(ThemeKey)
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
return ctx
}

父组件 provide

1
2
3
4
<script setup lang="ts">
import { provideTheme } from '@/composables/useTheme'
provideTheme()
</script>

子组件 inject

1
2
const { isDark, toggle } = useTheme()
// isDark: Ref<boolean>,toggle: () => void

类型完整推导,写错用法直接报红。

默认值

1
2
3
4
const ctx = inject(ThemeKey, {
isDark: ref(false),
toggle: () => {},
})

五、defineSlots 与 defineOptions

defineSlots:声明插槽类型

1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup lang="ts">
defineSlots<{
default(props: { item: User; index: number }): any
header(): any
}>()
</script>

<template>
<slot name="header" />
<div v-for="(item, index) in list" :key="item.id">
<slot :item="item" :index="index">{{ item.name }}</slot>
</div>
</template>

父组件使用时:

1
2
3
4
5
<List :list="users">
<template #default="{ item, index }">
{{ index }}. {{ item.name }} <!-- item: User,类型推导 -->
</template>
</List>

defineOptions:补充配置

<script setup> 里没法直接写 name、inheritAttrs 这些选项,用 defineOptions:

1
2
3
4
defineOptions({
name: 'UserCard',
inheritAttrs: false,
})

六、ref 模板引用类型

单个元素

1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup lang="ts">
import { ref } from 'vue'

const inputRef = ref<HTMLInputElement>()

function focus() {
inputRef.value?.focus()
}
</script>

<template>
<input ref="inputRef" />
</template>

组件实例

1
2
3
4
import type FormComp from './MyForm.vue'

const formRef = ref<InstanceType<typeof FormComp>>()
formRef.value?.submit()

v-for 里的 ref 数组

1
2
3
4
5
6
7
8
9
10
11
12
13
import { ref, onMounted } from 'vue'

const items = ref<HTMLLIElement[]>([])
const setItem = (el: any, idx: number) => {
if (el) items.value[idx] = el as HTMLLIElement
}
</script>

<template>
<li v-for="(x, i) in list" :key="x.id" :ref="el => setItem(el, i)">
{{ x.name }}
</li>
</template>

七、泛型组件(Generic Components)

Vue3.3+ 原生支持 <script setup> + <script generic>,能写带类型参数的组件。最典型场景是泛型表格、泛型选择器。

一个泛型表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script setup lang="ts" generic="T extends { id: number | string }">
import { ref, watchEffect } from 'vue'

const props = defineProps<{
data: T[]
columns: Array<{ key: keyof T; title: string }>
rowKey?: keyof T
}>()

const emit = defineEmits<{
rowClick: [row: T]
}>()
</script>

<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="String(col.key)">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id" @click="emit('rowClick', row)">
<td v-for="col in columns" :key="String(col.key)">
{{ row[col.key] }}
</td>
</tr>
</tbody>
</table>
</template>

父组件使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup lang="ts">
import GenericTable from './GenericTable.vue'
import type { User } from '@/types/user'

const users: User[] = [
{ id: 1, name: 'Tom', age: 18 },
{ id: 2, name: 'Jerry', age: 20 },
]

const columns = [
{ key: 'name' as const, title: '姓名' },
{ key: 'age' as const, title: '年龄' },
]
</script>

<template>
<GenericTable :data="users" :columns="columns" @row-click="onRow" />
</template>

调用时 T 自动推导为 User,columns 的 key 只允许填 User 的字段名(拼错立刻报红),@row-click 的回调参数也是 User。整个数据流类型闭环。

defineSlots 配合泛型

1
2
3
defineSlots<{
default(props: { row: T; index: number }): any
}>()

八、Vue Router 类型化路由

路由定义带类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
{
path: '/',
name: 'home',
component: () => import('@/views/HomeView.vue'),
},
{
path: '/user/:id',
name: 'user',
component: () => import('@/views/UserView.vue'),
props: true,
// 用 params 声明类型
meta: { requireAuth: true },
},
] as const

const router = createRouter({
history: createWebHistory(),
routes,
})

export default router

useRoute 的 params 类型

1
2
3
4
import { useRoute } from 'vue-router'

const route = useRoute()
route.params.id // 类型: string | string[]

增强路由 meta 类型

vue-router 默认的 meta 是 RouteMeta,可以在 vue-router.d.ts 增强:

1
2
3
4
5
6
7
8
9
// src/types/vue-router.d.ts
import 'vue-router'

declare module 'vue-router' {
interface RouteMeta {
requireAuth?: boolean
title?: string
}
}

之后所有路由的 meta.requireAuth 都有类型提示。

1
2
3
4
5
6
declare module 'vue-router' {
interface RouteNamedMap {
home: RouteRecordInfo<'home', '/', {}, {}>
user: RouteRecordInfo<'user', '/user/:id', { id: string }, {}>
}
}

配合 unplugin-vue-router 可以让 RouterLink to 的 path 也强类型化,但属于可选进阶配置。

九、TS 配置关键项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// tsconfig.app.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"verbatimModuleSyntax": true, // 强制 type-only import
"isolatedModules": true,
"skipLibCheck": true,
"jsx": "preserve",
"useDefineForClassFields": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "env.d.ts"]
}

关键点:

  • strict: true:开启全套严格模式,是 TS 类型安全的基石。
  • verbatimModuleSyntax:强制 import type,运行时不引入无用模块。
  • paths:配合 vite.config.ts 的 alias,让 IDE 跳转和类型检查一致。

十、类型速查表

场景 写法
props defineProps<{ title: string; size?: 'sm' | 'md' }>()
props 默认值 withDefaults(defineProps<P>(), { title: '默认' })
emits defineEmits<{ update: [v: string]; success: [] }>()
v-model const m = defineModel<string>()
provide/inject const key: InjectionKey<Ctx> = Symbol() + provide(key, ctx)
插槽类型 defineSlots<{ default(p: { item: T }): any }>()
组件实例 ref ref<InstanceType<typeof Comp>>()
泛型组件 <script setup lang="ts" generic="T extends ...">
路由 meta 在 vue-router.d.ts 增强 RouteMeta

小结

TypeScript 在 Vue3 里要发挥价值,关键不在”会不会写类型”,而在把这些类型用到组件边界的每一处:

  1. defineProps 用泛型 + withDefaults,比 Options 写法类型更准。
  2. defineEmits 用类型字面量,事件名和参数都有提示。
  3. defineModel 让 v-model 双向绑定写得最少、类型最完整。
  4. provide / inject 配合 InjectionKey,跨层级注入也类型安全。
  5. defineSlots + defineOptions 补齐配置项和插槽类型。
  6. 泛型组件 <script generic> 是表格、选择器这类高复用组件的标配。
  7. Vue Router 通过 declare module 增强 RouteMeta,让路由 meta 也类型化。

至此,Vite + Vue3 + Pinia + TypeScript 这套现代前端技术栈的实战四部曲就完成了:

  • 第一篇:从零搭工程化骨架。
  • 第二篇:Composition API 的响应式与逻辑复用。
  • 第三篇:Pinia 的状态管理与持久化。
  • 第四篇(本文):TS 类型进阶,让整个项目在编译期就规避大量错误。

这套四部曲可以当作团队技术栈入门的统一教材,新成员照着走一遍,就能写出风格一致、类型完备的 Vue3 项目。