刚开始写ts 代码时不太明确类型声明文件存放在哪里,今天整理下,类型声明文件存放地址
全局声明的类型文件
全局类型声明文件:用于这个项目通用的基础类型声明(如全局工具类型,业务实例类型) 我是将全局存放的类型声明文件存放在src/types/* 目录下
type Nullable<T> = T |null; // 全局工具类型
interface User{ // 业务实体类型
id:string;
name:string;
email:string;
}
需要再tsconfig.json 的include 中添加该路径
Vite 相关类型声明
存放在根目录 vite-env.d.ts
用于定义Vite环境变量 以及 Vite 客户端扩展类型
interface ImportMetaEnv{
readonly VITE_API_BASE_URL: string;
readonly VITE_MODE: 'development' | 'production';
}
interface ImportMeta{
env:ImportMetaEnv
}
组件类型声明
一般存放在组件的同一级目录 设置src/components/组件名/
src/
components/
Button/
Button.vue
types.ts
公共函数类型声明
我的公共函数存放在src/utils/ 所以类型声明也放在同一级目录
Api接口类型声明
同样道理 src/api/types.ts 存放公共的api 类型声明
src/api/user/type.ts 存放具体模块的类型声明
第三方类型声明的补充
存放目录为src/types/three-part.d.ts
对于一些第三方没有给出的类型提示的,或者需要进行补充的存放在 src/types 下
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
declare module "*.scss" {
const scss: Record<string, string>;
export default scss;
}
declare module 'untyped-library' {
export function someFunction(): void;
}
目录结构
src/
├── types/
│ ├── global.d.ts # 全局基础类型
│ ├── components/ # 组件类型(可选集中管理)
│ ├── utils.d.ts # 工具函数类型
│ └── third-party.d.ts # 第三方库类型扩展
├── vite-env.d.ts # Vite 环境变量类型
├── api/
│ ├── user/
│ │ ├── types.d.ts # 用户相关接口类型
│ │ └── index.ts
├── components/
│ ├── Button/
│ │ ├── Button.vue
│ │ └── types.ts # 组件私有类型(方案1)
└── utils/
├── http.ts
└── types.ts # 工具函数类型(方案2)
tsconfig.json 配置
需要配置typeRoots include
{
compilerOptions:{
//xxxx
"typeRoots": ["./node_modules/@types", "./types"]
},
include:{
"types/**/*.d.ts",
"types/**/*.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.d.ts"
}
}