Vue3 Script Setup+TS报错:Type 'string'无法赋值给'Stuff | undefined'
解决Vue3 script setup中Props类型不匹配的TS错误
问题原因
你定义的变量被TypeScript默认推断为宽泛的string类型,而非你声明的Stuff联合类型('item' | 'box' | 'area'),导致传入组件kind prop时类型不兼容。
解决办法
以下几种方式都可以修复这个类型错误:
显式指定变量类型
直接给变量标注Stuff类型,让TS明确其类型范围:import type { Stuff } from './path-to-types' const currentKind: Stuff = 'item'之后在模板中传入
<SearchBar :kind="currentKind" />即可。使用类型断言缩小范围
如果变量是动态赋值或无法直接指定类型,可通过断言强制缩小类型:// 脚本中断言 const currentKind = 'item' as Stuff或者在模板中直接断言(更推荐在脚本层处理):
<SearchBar :kind="currentKind as Stuff" />用const断言推断字面量类型
若变量是固定字面量值,使用as const让TS推断为具体的字面量类型,而非宽泛的string:const currentKind = 'item' as const由于
'item'是Stuff的成员,TS会自动兼容该类型。检查Props定义正确性
确保SearchBar组件中kindprop的类型定义正确:import { defineProps, PropType } from 'vue' import type { Stuff } from './path-to-types' const props = defineProps({ kind: { type: String as PropType<Stuff>, required: false // 根据业务需求设置是否必填 } })
内容的提问来源于stack exchange,提问作者LovelyAndy
相关产品推荐
相关产品推荐

