Skip to content

环境模块(Ambient Module)

一句话解释

环境模块(declare module)描述 JS 库的类型,无实现——用于 .d.ts 文件。

用大白话说

环境模块声明告诉 TypeScript 关于运行时存在(通常是 JS 库)但无 TypeScript 类型的模块。它是仅类型的描述——无实现。语法:declare module "library-name" { export function foo(): void; }

这就是 .d.ts 文件包含的内容——JS 库的类型声明。DefinitelyTyped(@types/* 包)为数千个库提供环境声明。没有环境声明,导入 JS 库会给你 any 类型。有了它们,你获得完整类型安全。你也可以为内部 JS 模块编写自己的环境声明。

示例

typescript
// my-utils.d.ts — ambient declaration for a JS file
declare module "my-utils" {
  export function format(date: Date): string;
  export const VERSION: string;
  export type Config = { debug: boolean };
}

// Now TypeScript knows the types
import { format, VERSION, Config } from "my-utils";
const s: string = format(new Date()); // Typed!
const v: string = VERSION; // Typed!

declare module 描述 JS 模块的类型,无实现。导入无类型 JS 库时提供类型安全。

常见混淆

  • 容易混淆的对象: 模块增强

    关键区别: 环境模块为完全没有类型的模块创建类型声明。模块增强向已有类型的模块添加内容。环境创建;增强扩展。无类型 JS 用环境,扩展已类型化库用增强。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表