You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript组件Props字面量类型与默认值配置报错求助

Vue3 + TypeScript 组件字面量类型Prop报错解决办法

问题根源

你遇到的错误主要来自两个点:

  1. PropType导入错误:你从@vue/composition-api导入了PropType,但这个包是给Vue2做兼容用的,Vue3的类型定义应该直接从vue包导入。
  2. 默认值类型未约束: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:使用

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:45:32