Vue3中defineProps搭配withDefaults出现TS错误与ESLint报错原因咨询
错误原因及修复方案
错误1:ESLint提示“Prop 'duration' requires default value to be set”
- 原因:ESLint规则
vue/require-default-prop规定,所有非必填且非布尔类型的props必须设置默认值。你的duration是可选的字符串枚举类型,不属于布尔类型,因此触发了这条规则——即使它是可选的,ESLint要求为其提供默认值,避免未传入时出现undefined。
错误2:TypeScript类型不匹配报错
- 原因:在Vue 3中,当使用
withDefaults配合defineProps<Props>()时,若props包含可选布尔属性(如initialAnimation),会出现类型推断冲突。defineProps会自动将可选布尔props标记为支持布尔属性语法(即可以不带值使用,如<MyComponent initialAnimation>),而withDefaults设置默认值后,该prop的类型会被推断为“必选且带有默认值”,两者的类型定义无法兼容。
修复后的代码
<script setup lang="ts"> import { computed } from 'vue'; type Props = { duration?: '0'|'0.5'|'1'|'1.5'|'2'|'2.5'|'3'|'4'|'5'|'6'|'7'|'8'|'9'|'10', initialAnimation?: boolean, additionalAnimateClasses?: string }; const props = withDefaults(defineProps<Props>(), { // 修复ESLint错误:为duration添加默认值 duration: '0', initialAnimation: true, additionalAnimateClasses: '' }); </script>
额外说明
如果上述代码仍存在TypeScript错误,建议升级Vue到3.3或更高版本(该版本优化了withDefaults与defineProps的类型推断)。若无法升级,可改用defineProps的对象语法来明确类型和默认值:
<script setup lang="ts"> import { computed, PropType } from 'vue'; type DurationType = '0'|'0.5'|'1'|'1.5'|'2'|'2.5'|'3'|'4'|'5'|'6'|'7'|'8'|'9'|'10'; const props = withDefaults(defineProps({ duration: { type: String as PropType<DurationType>, default: '0' }, initialAnimation: { type: Boolean, default: true }, additionalAnimateClasses: { type: String, default: '' } }), {}); </script>
内容的提问来源于stack exchange,提问作者Mohammad A. Apu
相关产品推荐
相关产品推荐

