Vue3 Composition API(Script Setup+TS)如何设置嵌套Props默认值?
问题分析与解决方案
错误原因
触发ts(2345)类型错误的核心原因是**DEFAULTS的类型断言与withDefaults要求的参数类型不匹配**:
WindowType中的config是可选属性,类型为WindowConfig | undefined,当你将DEFAULTS断言为WindowType时,config的类型被拓宽为WindowConfig | undefined。- Vue的
withDefaults第二个参数需要符合InferDefaults<WindowType>类型,对于可选的对象属性,该类型要求默认值必须是非undefined的对象类型(即纯WindowConfig),不允许包含undefined的可能性。 - 两者类型不兼容,因此抛出类型错误。
可行解决方案
方案1:移除DEFAULTS的类型断言
让TypeScript自动推断DEFAULTS的类型,无需手动断言:
<script setup lang="ts"> export interface WindowConfig { showTitlebar: boolean } export interface WindowType { title: string, config?: WindowConfig } const DEFAULTS = { title: 'Default title', config: { showTitlebar: true } } const props = withDefaults(defineProps<WindowType>(), DEFAULTS) </script>
方案2:断言为InferDefaults<WindowType>类型
显式让DEFAULTS匹配withDefaults要求的参数类型:
<script setup lang="ts"> import type { InferDefaults } from 'vue' export interface WindowConfig { showTitlebar: boolean } export interface WindowType { title: string, config?: WindowConfig } const DEFAULTS = { title: 'Default title', config: { showTitlebar: true } as WindowConfig } as InferDefaults<WindowType> const props = withDefaults(defineProps<WindowType>(), DEFAULTS) </script>
方案3:使用工厂函数定义对象默认值(官方推荐)
对于对象类型的默认值,Vue官方推荐用工厂函数返回,避免多实例共享对象引用的问题,同时也能自然匹配类型:
<script setup lang="ts"> export interface WindowConfig { showTitlebar: boolean } export interface WindowType { title: string, config?: WindowConfig } const props = withDefaults(defineProps<WindowType>(), { title: 'Default title', config: () => ({ showTitlebar: true }) }) </script>
相关文档指引
- Vue 3官方文档:Props 默认值章节
- Vue 3 TypeScript 指南:为组件 Props 标注类型章节
内容的提问来源于stack exchange,提问作者Daniel Tate
相关产品推荐
相关产品推荐

