登录
首页 >  文章 >  前端

Vue3 TS 中如何使用 defineProps 做严格类型声明?

时间:2026-04-06 19:35:19 251浏览 收藏

在 Vue 3 + TypeScript 项目中,要真正实现 props 的严格类型安全,必须摒弃传统的运行时对象配置写法,转而采用泛型方式配合 `defineProps` 和 `withDefaults` 进行编译期类型声明——推荐使用语义清晰的 `interface` 定义可复用、易维护的 Props 结构,为函数、对象、数组等复杂类型显式标注(如 `(id: number) => void` 或 `User[]`),并通过 `withDefaults` 精确绑定默认值(类型必须完全匹配),从而让 IDE 智能提示、模板访问和编译检查全部生效,彻底杜绝 `any` 泛滥与运行时隐式错误。

Vue3 中 defineProps 怎么在 TS 中使用?严格类型声明实战

Vue 3 中 defineProps 在 TypeScript 下的严格类型声明,核心是**用泛型替代运行时对象配置**,让类型检查发生在编译期,而非仅靠 Vue 运行时校验。推荐直接使用接口(interface)或内联类型字面量定义 props 结构,配合 withDefaults 处理默认值,兼顾类型安全与开发效率。

用 interface 定义可复用的 Props 类型

适合多处使用、结构较复杂或需团队协作的组件。接口名用 PascalCase,字段名保持语义清晰:

interface UserCardProps {
  id: number;
  name: string;
  avatar?: string;
  status: 'active' | 'inactive' | 'pending';
  onSelect?: (id: number) => void;
}

const props = defineProps();

这样写,IDE 能精准提示每个字段类型、是否可选、函数参数,模板中访问 props.nameprops.onSelect?.(123) 都有完整类型保障。

带默认值的严格类型:withDefaults + 泛型

defineProps() 不支持默认值;必须搭配 withDefaults。它只接受泛型式 props 声明,不能和对象式混用:

  • 先定义含可选字段的泛型类型(? 表示可选)
  • withDefaults 第二个参数中提供默认值对象,键名必须与泛型中字段完全一致
  • 默认值类型必须严格匹配字段声明类型(如 count?: number 对应 count: 0,不能是 '0'

const props = withDefaults(
  defineProps<{
    title: string;
    count?: number;
    theme?: 'light' | 'dark';
  }>(),
  {
    count: 1,
    theme: 'light'
  }
);

处理函数、对象、数组等复杂类型

基础类型(stringnumber)直接写即可;函数、自定义对象、数组需明确标注,避免推导为 any

  • 函数类型:直接写 (id: number) => void,不加 Function 构造器
  • 自定义对象:用已定义的接口(如 User),或内联对象类型 { id: number; name: string }
  • 数组:写成 User[]Array,不要用 Arrayany[]
  • 可为空对象:用 Record | null 或更精确的 Partial | null

interface Product { id: number; name: string }
const props = defineProps<{
  items: Product[];
  onRemove: (id: number) => void;

避免常见错误写法

以下写法看似能跑,但会削弱类型安全性或导致 IDE 提示失效:

  • defineProps({ title: String }) —— 运行时写法,TS 无法推导 props.titlestring 还是 string | undefined
  • defineProps<{ items: any[] }>() —— 用 any 等于放弃类型检查
  • withDefaults(defineProps({ title: String }), { title: 'x' }) —— 混用泛型与对象式,TS 类型丢失,且运行时报错
  • ❌ 默认值类型不匹配:泛型写 count?: number,却给 count: '1' —— 编译报错

本篇关于《Vue3 TS 中如何使用 defineProps 做严格类型声明?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>