启用 "strict": true 是开启 TypeScript 严格模式最核心方式,需同时配置 skipLibCheck、moduleResolution、baseUrl/paths、include 和 types,并在 env.d.ts 中声明 .vue 类型。

直接在 tsconfig.json 的 compilerOptions 中启用 "strict": true 即可,这是开启 TypeScript 严格模式最核心、最有效的方式。它会一并激活一系列子检查项(如 noImplicitAny、strictNullChecks、strictFunctionTypes 等),大幅提升类型安全性。
关键配置项必须补全
仅开 strict 不够,还需确保以下几项明确存在且合理:
-
"skipLibCheck": true:跳过对 node_modules 中类型声明的检查,大幅提升编译速度,是实际项目中的通用做法; -
"moduleResolution": "node":确保模块解析行为与 Node.js 一致,避免import路径报错; -
"baseUrl": "."和"paths":配合 Vite 的别名(如@/指向src/),让 TypeScript 也能识别路径别名,否则 VS Code 会提示“无法找到模块”; -
"include"必须包含.vue文件:例如"src/**/*.vue",否则组件中的类型不会被检查; -
添加
"types": ["node", "vite/client"]:显式引入 Node 和 Vite 的全局类型,避免process、import.meta.env等报错。
Vue 特有类型支持不能少
在 src/env.d.ts 中必须有标准声明,否则 .vue 文件无法被正确推导类型:
Vue 3 组合式 API 与 最佳实践,涵盖代码组织、useXxx 模式、组合式函数设计、Store 集成、响应式优化及功能抽取。
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
这个文件让 TypeScript 知道所有 .vue 文件默认导出一个组件类型,defineProps、defineEmits 才能获得完整类型提示。
立即学习“前端免费学习笔记(深入)”;
验证是否生效的小技巧
改完配置后,可以快速验证严格模式是否起作用:
- 在
setup()或<script setup>中写let x;—— 应立刻报错Variable 'x' is used before being assigned; - 定义一个函数但不写返回类型,再让它隐式返回
undefined—— 若开启strictNullChecks,调用处可能提示类型不兼容; - 访问一个可能为
null的值的属性(如user?.name.toUpperCase())—— 若未做非空断言或可选链处理,会提示错误。

















