全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 8 分钟 ✍️ juanwangdev

TypeScript 声明文件基础

声明文件是 TypeScript 与 JavaScript 交互的桥梁,下面梳理核心用法。

.d.ts 作用

声明文件(.d.ts)为没有类型信息的 JavaScript 库提供类型描述,使 TS 编译器能够进行类型检查与智能提示。

TypeScript
// lodash.d.ts
declare function chunk(array: any[], size: number): any[][];
declare function debounce<T extends (...args: any[]) => void>(
  func: T,
  wait?: number
): T;

declare const _: {
  chunk: typeof chunk;
  debounce: typeof debounce;
};

export = _;

注意:声明文件仅包含类型信息,不包含实现代码,编译后不产生 .js 文件。

declare 关键字

声明全局变量

TypeScript
declare const API_URL: string;
declare function initApp(config: object): void;
declare namespace utils {
  function format(str: string): string;
}

声明全局类

TypeScript
declare class EventEmitter {
  on(event: string, listener: (...args: any[]) => void): this;
  emit(event: string, ...args: any[]): boolean;
}

模块声明

声明模块

TypeScript
// 声明一个第三方模块
declare module "my-lib" {
  export function create(options: object): void;
  export const VERSION: string;
}

使用:

TypeScript
import { create, VERSION } from "my-lib";
create({ debug: true });

声明模块扩展

TypeScript
// 扩展 Express Request 类型
declare global {
  namespace Express {
    interface Request {
      user: {
        id: string;
        role: string;
      };
    }
  }
}

第三方库声明

安装 @types 包

Bash
npm install --save-dev @types/lodash
npm install --save-dev @types/node

手动编写声明文件

当没有现成 @types 时,在项目根目录创建 types/ 目录:

JSON
src/
types/
  my-lib.d.ts
tsconfig.json

tsconfig.json 配置:

TypeScript
{
  "compilerOptions": {
    "typeRoots": ["./types", "./node_modules/@types"]
  }
}

声明文件最佳实践

规则说明
只写类型声明文件不应包含运行时逻辑
使用 declare所有全局声明必须用 declare 前缀
导出类型模块声明文件必须 export 至少一个值
避免 any尽可能使用精确类型
保持同步库更新时声明文件需同步更新

常见声明模式

函数重载声明

TypeScript
declare function parse(input: string): object;
declare function parse(input: Buffer): object;

泛型声明

TypeScript
declare function fetch<T>(url: string): Promise<T>;

interface User { id: string; name: string; }
const user = await fetch<User>("/api/user");

类与接口声明

text
declare interface LoggerOptions {
  level: "debug" | "info" | "warn" | "error";
}

declare class Logger {
  constructor(options: LoggerOptions);
  log(msg: string): void;
  static create(options: LoggerOptions): Logger;
}

要点总结

  • .d.ts 声明文件为 JS 库提供类型信息,编译后消失
  • declare 关键字声明全局变量/函数/类,不产生运行时代码
  • declare module 声明第三方模块或扩展现有模块类型
  • 第三方库优先安装 @types/* 包,没有时手动编写声明文件
  • 声明文件只应包含类型信息,不应包含运行时逻辑

📝 发现内容有误?点击此处直接编辑

← 上一篇 TypeScript 常用内置工具类型
下一篇 → TypeScript 深度类型编程
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库