Vue3+TypeScript创建组件触发TS2769无匹配重载错误怎么解决?
问题原因及解决方案
错误根因
该TS报错本质是Vue类型定义和当前TypeScript配置/项目依赖不匹配,导致选项式API的data字段未被类型系统识别。
解决方案
方案1:修复现有选项式写法的配置
- 重装依赖修复类型损坏
删除项目下的node_modules文件夹、package-lock.json/pnpm-lock.yaml/yarn.lock文件,重新执行依赖安装命令即可。 - 校验
tsconfig.json配置,确保compilerOptions包含以下必填项:
{ "compilerOptions": { "strict": true, "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true } }
- 补充Vue类型声明文件
项目src目录下新增env.d.ts文件,写入以下内容:
/// <reference types="vite/client" /> // 如使用webpack/vue-cli则替换上方为 /// <reference types="webpack-env" /> declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, any> export default component }
方案2:改用Vue3推荐的<script setup>语法(原生适配TS)
直接重写组件代码,完全规避选项式API的类型兼容问题,代码如下:
<script setup lang="ts"> import { ref } from 'vue' // 定义props类型+默认值 interface Props { msg?: string } const props = withDefaults(defineProps<Props>(), { msg: '' }) // 定义响应式变量,替代原data选项 const name = ref('Link') </script>
内容的提问来源于stack exchange,提问作者Dimitri
相关产品推荐
相关产品推荐

