3.1 TS2307: Cannot find module '@/xxx' or its corresponding type declarations
原因:Vite 的 alias 配了,但 TS 的 paths 没配。两者必须同时配。
解决:tsconfig.json 加:
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
}
}
Vite 配置见 ../frontend/vite.config.ts:8。修改
paths后 VSCode 需要重启 TS Server(Cmd+Shift+P → Restart TS Server)。
3.2 TS2322 / TS2345 类型不兼容
定位思路:
- 报错行号往往指向赋值/传参点,真正错误在上游推导
- 鼠标悬停
const x = ...看 TS 推出的实际类型 - 高频场景:
useState<T>()没传泛型,推成undefined- antd
Form的onFinishvalues 类型默认any,要<Form<FieldType>> - 数组
[]推成never[],要useState<User[]>([])
修法:显式标注泛型,而不是在赋值点强转。
3.3 JSX element implicitly has type 'any' / Cannot use JSX unless '--jsx' flag is provided
原因:tsconfig.json 缺 "jsx": "react-jsx"(React 17+ 写法)。
对比:
"jsx": "react"— 老写法,需要import React from 'react'"jsx": "react-jsx"— 现代写法,自动注入
3.4 'X' is declared but its value is never read. (TS6133)
原因:noUnusedLocals / noUnusedParameters 开启。
修法:
- 直接删未使用变量(最佳)
- 改成
_x占位(参数列表里有用,如 reducer 的 state) - ❌ 不要
// @ts-ignore压住
3.5 类型声明文件缺失:Could not find a declaration file for module 'xxx'
解决(按顺序尝试):
npm i -D @types/xxx- 没有官方类型,在
src/types/shims.d.ts写:declare module 'xxx'; - 想要严谨类型就手写一份:
declare module 'xxx' { export function foo(x: number): string; }
3.6 与本项目相关:.md 引入报错
../frontend/vite.config.ts:17 通过 assetsInclude 把 md 当资源,但 TS 不认。
解决:在 src/vite-env.d.ts 加:
declare module '*.md?raw' { const src: string; export default src; }
declare module '*.md' { const src: string; export default src; }
3.7 Property 'env' does not exist on type 'ImportMeta'
原因:Vite 的 import.meta.env 类型默认有,但自定义环境变量没声明。
解决:src/vite-env.d.ts:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
3.8 Cannot redeclare block-scoped variable
原因:全局没有 export,TS 把文件当 script 而非 module,同名变量在多文件冲突。
修法:任意一行加 export {} 把文件变成 module。
3.9 Type instantiation is excessively deep and possibly infinite
原因:复杂泛型递归,常见于 zod / yup 的复杂 schema。
解决:
- 在出错点显式断言中间类型
- 拆分复杂类型为多个小类型
- TS 5.x 升级后通常缓解
3.10 tsc -b vs tsc 区别
本项目 package.json 用 tsc -b(Project References 模式)。
-b增量构建,看tsconfig.tsbuildinfo缓存- 报错诡异时删
*.tsbuildinfo重新构建 - CI 上首次构建慢,后续快