当前位置: 首页 > news >正文

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’; 都发生了什么事情?

  1. import { Button } from 'antd'; 编译器发现你在代码中引入了 antd 组件库里的 Button 组件。编译器会去查找 antd 这个包对应的类型声明文件,通常是 node_modules/antd/index.d.ts 或者 node_modules/antd/es/button/index.d.ts 等。
  2. TS 根据这些类型定义检查你代码中对 Button 的使用是否合法(比如属性类型、事件回调等)。
  3. 如果类型没问题,继续编译。

TypeScript 找类型声明文件的流程

  1. 从 package.json 的 “types” 或 “typings” 字段查找
{"types": "lib/index.d.ts"
}
  • 以我的项目中的 my-react-app/node_modules/antd/package.json 为例
    在这里插入图片描述
  1. 如果没有 “types” 或 “typings” 字段
    编译器会尝试查找包内 index.d.ts 文件(或者 “main” 指定的 JS 文件同目录下的 .d.ts 文件)。
    如果找不到,则会报错“找不到模块的类型声明”。 Cannot find module 'antd' or its corresponding type declarations.
http://www.dtcms.com/a/325031.html

相关文章:

  • 糖果大冒险:公平分发的智慧挑战
  • Stagewise使用指南:从项目集成到效能跃迁的深度解析
  • 【算法题】:和为N的连续正数序列
  • AI大模型-提示词工程
  • 01 词法分析陷阱:C编程中的符号误解
  • 深度解析 Spring Boot 循环依赖:原理、源码与解决方案
  • PhotoDirector 安卓版:功能强大的照片编辑与美化应用
  • TypeScript中的type和interface的区别是什么?
  • Shell脚本-数组定义
  • OpenEnler等Linux系统中安装git工具的方法
  • DDR中的POD与ODT
  • 分布式事务原理(高并发系统下的数据一致性保障)
  • 一、线性规划
  • 免费数字人API开发方案
  • 高精度计算+快速幂算法
  • 【算法题】:斐波那契数列
  • 【langchain】如何给langchain提issue和提pull request?
  • SpringIoc 实践和应用--XML配置
  • 数据结构-deque(双端队列)和queue(队列)区别
  • Flask多进程数据库访问问题详解
  • spring全家桶使用教程
  • Lua语言元表、协同程序
  • 密码学的数学基础2-Paillier为什么产生密钥对比RSA慢
  • SQL三剑客:DELETE、TRUNCATE、DROP全解析
  • 深度相机---双目深度相机
  • 浏览器CEFSharp+X86+win7 之 浏览器右键菜单(六)
  • Mysql笔记-存储过程与存储函数
  • vulnhub-doubletrouble靶场攻略
  • Linux C文件操作函数
  • 谷歌DeepMind发布Genie 3:通用型世界模型,可生成前所未有多样化的交互式虚拟环境