声明文件(.d.ts)
什么是声明文件
声明文件用于描述JavaScript代码的类型信息,本身不包含实现代码。文件扩展名为.d.ts。
三种获取类型声明的方式
- 内置类型:TypeScript自带的DOM、ES等类型定义
- DefinitelyTyped:社区维护的类型声明仓库,通过
@types/包名安装 - 自带类型:越来越多的npm包自带TypeScript类型定义
# 安装第三方类型声明
pnpm add -D @types/node
pnpm add -D @types/express
bash
自定义声明文件
// env.d.ts - 环境变量类型声明
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_APP_TITLE: string
}
// shims-vue.d.ts - Vue文件类型声明
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
typescript
tsconfig.json配置
核心配置项
{
"compilerOptions": {
"target": "ES2022", // 编译目标
"module": "ESNext", // 模块系统
"moduleResolution": "bundler", // 模块解析策略
"strict": true, // 严格模式(推荐开启)
"jsx": "preserve", // JSX处理方式
"esModuleInterop": true, // ES模块兼容
"skipLibCheck": true, // 跳过库类型检查(加速编译)
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"] // 路径别名
}
},
"include": ["src/**/*.ts", "src/**/*.vue"],
"exclude": ["node_modules", "dist"]
}
json
strict模式包含的检查
开启strict: true相当于同时开启以下所有检查:
- strictNullChecks:null和undefined不能赋值给其他类型
- noImplicitAny:禁止隐式any类型
- strictFunctionTypes:函数参数类型严格检查
- strictBindCallApply:bind/call/apply严格检查
- strictPropertyInitialization:类属性必须初始化
- noImplicitThis:禁止隐式any的this
↑