index.d.ts 是什么?作用 + 怎么生成?
文章目录
- index.d.ts
- 什么是 index.d.ts?
- 生成方式
- 手写
- 自动
- import { Button } from 'antd'; 都发生了什么事情?
- TypeScript 找类型声明文件的流程
index.d.ts
什么是 index.d.ts?
index.d.ts 是 TypeScript 的声明文件(Declaration File)。
它只包含类型声明,不包含具体实现代码。用来告诉 TypeScript 编译器某个模块或库中有哪些类型、接口、函数、变量等,让使用者在编写代码时能获得类型检查和自动补全。
- 使用场景
比如 npm 发包(可以看这个视频 BV1PK411u7CX 了解发包流程)的时候,.d.ts 文件描述了库的类型接口。这样别人用 TS 时,自动获得类型支持。
生成方式
手写
- 我的 hello.ts
// hello.ts
export function greet(name: string): string {return `Hello, ${name}!`;
}
- 手写对应的 index.d.ts
// index.d.ts
export declare function greet(name: string): string;
export declare function … 表示声明这个函数存在,但没有具体实现(实现写在 .ts 或 .js 里)。
这个文件告诉 TypeScript 编译器:greet 是一个接收字符串参数并返回字符串的函数。如果别人用我的库或模块,TS 就能根据这个声明做类型检查和自动补全。
自动
- 代码布局
- 具体代码
// hello.ts
function greet(name: string): string {return `Hello, ${name}!`;
}const user = "Alice";
console.log(greet(user))
// tsconfig.json
{"compilerOptions": {"declaration": true, // 这一句很关键"outDir": "dist","emitDeclarationOnly": false,"target": "ES6","module": "commonjs"},"include": ["src"]
}
执行 tsc 之后,自动生成两个文件:
(1)dist/hello.js — 编译后的 JS 代码
(2)dist/hello.d.ts — 自动生成的声明文件,内容类似:
import { Button } from ‘antd’; 都发生了什么事情?
import { Button } from 'antd';
编译器发现你在代码中引入了 antd 组件库里的 Button 组件。编译器会去查找 antd 这个包对应的类型声明文件,通常是 node_modules/antd/index.d.ts 或者 node_modules/antd/es/button/index.d.ts 等。- TS 根据这些类型定义检查你代码中对 Button 的使用是否合法(比如属性类型、事件回调等)。
- 如果类型没问题,继续编译。
TypeScript 找类型声明文件的流程
- 从 package.json 的 “types” 或 “typings” 字段查找
{"types": "lib/index.d.ts"
}
- 以我的项目中的 my-react-app/node_modules/antd/package.json 为例
- 如果没有 “types” 或 “typings” 字段
编译器会尝试查找包内 index.d.ts 文件(或者 “main” 指定的 JS 文件同目录下的 .d.ts 文件)。
如果找不到,则会报错“找不到模块的类型声明”。Cannot find module 'antd' or its corresponding type declarations.