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

Vue 3.2 + TypeScript使用defineProps<Iprops>报错求助

解决方案:Vue 3.2 + TypeScript 中 defineProps 类型定义报错问题

问题原因

  1. 你的 Vue 3.2 版本可能低于 3.2.34 —— 该版本才正式支持 defineProps 直接传入类型参数的语法;
  2. 分开的 <script> 标签中定义的接口无法被 <script setup> 的编译流程识别,因为 <script setup> 存在作用域隔离机制。

可行解决方案

方案1:升级Vue并合并脚本

将Vue升级到3.2.34或更高版本,同时把接口定义移到 <script setup> 内部:

<!-- AppButton.vue -->
<script lang="ts" setup>
interface IProps {
  buttonType?: string;
  size?: string;
  disabled?: boolean;
  loading?: boolean;
}

const props = defineProps<IProps>();
</script>

方案2:不升级Vue,使用对象式定义Props

如果无法升级Vue版本,改用 defineProps 的对象写法,同时保留类型提示:

<!-- AppButton.vue -->
<script lang="ts" setup>
import type { PropType } from 'vue';

// 定义Props的运行时校验
const props = defineProps({
  buttonType: {
    type: String,
    default: 'default'
  },
  size: {
    type: String,
    default: 'medium'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// 可选:定义接口做类型断言,获得更精准的类型提示
interface IProps {
  buttonType?: string;
  size?: string;
  disabled?: boolean;
  loading?: boolean;
}

const typedProps = props as IProps;
</script>

方案3:用ExtractPropTypes自动推导类型

借助Vue内置的 ExtractPropTypes 工具类型,从对象式Props定义中自动推导类型:

<!-- AppButton.vue -->
<script lang="ts" setup>
import type { ExtractPropTypes } from 'vue';

const props = defineProps({
  buttonType: String,
  size: String,
  disabled: Boolean,
  loading: Boolean
});

// 自动从Props定义推导类型
type IProps = ExtractPropTypes<typeof props>;
</script>

额外配置检查

确保你的 tsconfig.json 中包含以下配置,避免类型解析异常:

{
  "compilerOptions": {
    "strict": true,
    "types": ["vue"]
  },
  "vueCompilerOptions": {
    "target": 3
  }
}

内容的提问来源于stack exchange,提问作者Hamed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:39:36