Vue3组合式API+TypeScript:如何为Props设置数组默认值
Vue3组合式API+TypeScript中Props空数组默认值的正确设置方法
出现这个错误的核心原因是:直接赋值[]时TypeScript会将其推断为never[],同时Vue要求引用类型(数组、对象)的props默认值必须通过工厂函数返回(避免多个组件实例共享同一个引用对象)。以下是两种正确的解决方式:
方式1:使用defineProps配置项+工厂函数
先明确Props接口中数组的元素类型,再通过工厂函数返回空数组并匹配接口类型:
interface IProps { // 明确数组元素类型,比如string、自定义类型等 things: string[]; } const props = defineProps<IProps>({ things: { type: Array, // 用工厂函数返回空数组,通过类型断言让TS匹配接口定义 default: () => [] as string[] } });
方式2:使用withDefaults宏(Vue3.3+推荐)
Vue3.3及以上版本提供的withDefaults宏可以更简洁地处理默认值,自动匹配接口类型:
interface IProps { things: string[]; } // 直接通过withDefaults指定默认值,工厂函数返回空数组即可 const props = withDefaults(defineProps<IProps>(), { things: () => [] });
自定义类型数组的情况
如果数组元素是自定义类型,只需在接口中明确类型即可:
interface Thing { id: number; name: string; } interface IProps { things: Thing[]; } const props = withDefaults(defineProps<IProps>(), { things: () => [] });
内容的提问来源于stack exchange,提问作者Galivan
相关产品推荐
相关产品推荐

