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

Vite+Vue项目中<script setup>混用withDefaults与defineProps报错求助

Vite+Vue项目中withDefaults与defineProps联用的类型错误解决

问题场景

开发Vite+Vue项目,使用WebStorm作为开发工具,在<script setup>中同时使用withDefaults和defineProps时出现类型错误,尽管开发模式下props功能正常,但类型校验报错需要解决。

代码示例

<script setup lang="ts">
interface testInterface {
  name: string;
  much?: number;
}

const definesProp = withDefaults(defineProps<testInterface>(), {
  name: 'jarry',
});
</script>

错误信息

Argument type DefineProps<testInterface, BooleanKey<testInterface>> is not assignable to parameter type DefineProps<Readonly<testInterface> & {}, keyof Readonly<testInterface> & {}>

解决方法

  • 调整WebStorm的TypeScript配置

    1. 打开File > Settings > Languages & Frameworks > TypeScript
    2. 选择Use TypeScript from node_modules,应用设置后重启WebStorm,确保编辑器使用项目本地的TypeScript版本,避免全局版本与项目依赖不兼容。
  • 修改props类型定义写法
    给defineProps的泛型添加Readonly包装,消除类型不匹配问题:

    <script setup lang="ts">
    interface testInterface {
      name: string;
      much?: number;
    }
    
    const props = withDefaults(defineProps<Readonly<testInterface>>(), {
      name: 'jarry',
    });
    </script>
    

    或者改用内联对象字面量定义props类型,写法更简洁且不易触发类型问题:

    <script setup lang="ts">
    const props = withDefaults(defineProps<{
      name: string;
      much?: number;
    }>(), {
      name: 'jarry',
    });
    </script>
    
  • 更新Vue相关依赖
    执行命令更新Vue及配套类型依赖,确保版本一致:

    npm update vue @vue/runtime-core
    

内容的提问来源于stack exchange,提问作者신재홍

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:00:15