Vue 3 中 defineProps 的 TypeScript 严格类型声明需用泛型替代运行时配置,推荐 interface 或内联类型配合 withDefaults;函数、对象、数组须显式标注类型,避免 any。

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.name 或 props.onSelect?.(123) 都有完整类型保障。
Element Plus Vue3 桌面组件库。在开发 Vue 3.x 页面时调用,使用 Element Plus 组件(如 el-button、el-input、el-form、el-table 等)。
带默认值的严格类型:withDefaults + 泛型
纯 defineProps<t>()</t> 不支持默认值;必须搭配 withDefaults。它只接受泛型式 props 声明,不能和对象式混用:
- 先定义含可选字段的泛型类型(
?表示可选) - 在
withDefaults第二个参数中提供默认值对象,键名必须与泛型中字段完全一致 - 默认值类型必须严格匹配字段声明类型(如
count?: number对应count: 0,不能是'0')
const props = withDefaults(
defineProps title: string;
count?: number;
theme?: 'light' | 'dark';
}>(),
{
count: 1,
theme: 'light'
}
);
处理函数、对象、数组等复杂类型
基础类型(string、number)直接写即可;函数、自定义对象、数组需明确标注,避免推导为 any:
- 函数类型:直接写
(id: number) => void,不加Function构造器 - 自定义对象:用已定义的接口(如
User),或内联对象类型{ id: number; name: string } - 数组:写成
User[]或Array<user></user>,不要用Array或any[] - 可为空对象:用
Record<string unknown> | null</string>或更精确的Partial<user> | null</user>
interface Product { id: number; name: string }
const props = defineProps items: Product[];
onRemove: (id: number) => void;
();
避免常见错误写法
以下写法看似能跑,但会削弱类型安全性或导致 IDE 提示失效:
- ❌
defineProps({ title: String })—— 运行时写法,TS 无法推导props.title是string还是string | undefined - ❌
defineProps()—— 用any等于放弃类型检查 - ❌
withDefaults(defineProps({ title: String }), { title: 'x' })—— 混用泛型与对象式,TS 类型丢失,且运行时报错 - ❌ 默认值类型不匹配:泛型写
count?: number,却给count: '1'—— 编译报错

















