TypeScript 词条目录
前端Wiki/词条/声明文件 .d.ts

声明文件 .d.ts

定义为 JS 代码补类型描述的文件:编译产物是 JS 时,靠它让 TS 项目获得类型提示

老库、第三方 package 多数只有 JS 产物。TS 找不到类型时会报「隐式 any」。声明文件就是补上「形状描述」:declare function $(sel: string): any; declare const version: string;。只要 .d.ts 在编译范围内(或包内自带 types 字段指向它),TS 就把它们当作有类型的模块使用。

社区有 DefinitelyTyped(@types/xxx)为几千个流行库维护声明,装 @types/jquery 后 jQuery 就有完整类型。给自己项目发布库时,用 tsc --emitDeclarationOnly 单独产出 .d.ts 并在 package.json 配 "types": "dist/index.d.ts"。全局声明(.d.ts 中的 declare)会污染全局空间,模块化声明用 export 更干净。

TypeScript
// global.d.ts —— 为无类型的 JS 全局代码补声明
declare function $(selector: string): HTMLElement;
declare const APP_VERSION: string;

// 为 CommonJS 模块补声明(modules.d.ts)
declare module 'old-lib' {
  export function init(config: { token: string }): void;
  export const version: string;
}

// 使用方
$('app').innerHTML = 'v' + APP_VERSION;
import { init } from 'old-lib';
init({ token: 'x' });      // ✓ 有类型提示了
⚠ 常见误区
🔗 相关词条tsconfig.json 配置npm 与 package.json第三方库类型
← 返回来源章节声明文件 .d.ts