withdefaults 是 vue 3 中为 defineprops 声明的 typescript 类型 props 设置运行时默认值的标准方式,它保留类型推导、明确标识可选性,并避免未传 prop 导致的 undefined 访问错误。

在 Vue 3 的 Composition API 中,withDefaults 是为使用 defineProps 声明的 TypeScript 类型 Props 设置默认值的标准方式。它不会破坏类型推导,还能让 IDE 正确提示可选性与默认行为。
为什么要用 withDefaults 而不是直接在类型里写 ?
TypeScript 接口或类型中的 ?: 只表示“该属性可选”,并不等于“有默认值”。Vue 运行时仍会把未传的 prop 当作 undefined,而组件内部若直接访问可能报错。用 withDefaults 才是真正告诉 Vue:“这个 prop 没传时应该用什么值”。
基本用法:配合 defineProps
先定义带类型的 props,再用 withDefaults 包裹:
完整的Galileo AI平台 TypeScript/JS SDK 参考,用于评估、观察和保护 GenAI 应用。适用于构建 Node.js 或 TypeScript 项目。
const props = withDefaults(
defineProps(),
{
count: 0,
disabled: false,
theme: 'light'
}
)
注意:title 没出现在默认值对象中 → 它仍是必传项;其余字段即使标了 ?,也因 withDefaults 获得了运行时默认值。
进阶技巧:函数默认值 & 泛型保持
默认值可以是函数(适合返回新对象/数组,避免响应式污染):
-
items: () => []—— 返回空数组,每次实例都独立 -
config: () => ({ timeout: 5000 })—— 避免多个组件共享同一对象引用
泛型 props 也能用(需显式标注类型):
type ListProps<t> = {
data: T[]
getKey?: (item: T) => string
}
const props = withDefaults(
defineProps<listprops>>(),
{
getKey: () => (item: string) => item
}
)</listprops></t>
常见陷阱提醒
- 默认值对象的键必须严格匹配 props 类型中的可选字段名,拼写错误或多余字段会报类型错误
- 不能给必填字段(没写
?)设默认值,否则 TS 会提示 “Type ‘xxx’ is not assignable to type ‘never’” - 在
<script setup></script>中,withDefaults必须和defineProps写在同一语句或紧邻位置,否则编译器可能无法正确推导










