Vue3+TypeScript组件Props字面量类型与默认值配置报错求助
Vue3 + TypeScript 组件字面量类型Prop报错解决办法
问题根源
你遇到的错误主要来自两个点:
- PropType导入错误:你从
@vue/composition-api导入了PropType,但这个包是给Vue2做兼容用的,Vue3的类型定义应该直接从vue包导入。 - 默认值类型未约束:TS把你写的
"lg"默认值推断成了宽泛的string类型,而非你定义的Size联合类型,导致props的类型推导混乱。
方案1:修正Options API代码
直接修改原有组件代码,解决类型不匹配问题:
<script lang="ts"> // 从vue导入正确的PropType import type { PropType } from "vue"; import { defineComponent } from "vue"; type Size = "sm" | "md" | "lg"; export default defineComponent({ name: "RoundedPicture", props: { src: { type: String, required: true, }, alt: { type: String, required: true, }, border: { type: String as PropType<Size>, required: false, // 把默认值断言为Size类型,让TS识别它属于联合类型成员 default: "lg" as Size, }, }, setup(props) { const BORDER_WIDTH_SIZE_MAPPING: Record<Size, string> = { sm: "p-0.5", md: "p-1", lg: "p-1.5", }; return { BORDER_WIDTH_SIZE_MAPPING, props }; }, }); </script>
方案2:使用
相关产品推荐
相关产品推荐

