Skip to content

声明文件与模块增强

中等 约 40 分钟

你将构建什么

一个为假设的无类型库编写的 .d.ts 文件,以及一个为 String 添加自定义方法的模块增强。

学习目标

  • 在 .d.ts 文件中编写环境声明
  • 为无类型导入声明模块形状
  • 增强现有接口(模块增强)
  • 理解三斜杠指令

前置要求

  • 接口和类型别名
  • ES 模块导入
  • 理解 'any' 与有类型的区别

步骤

  1. 1

    声明无类型模块

    创建一个 .d.ts 文件,声明无类型 JS 模块的形状。这让你能以完整类型安全的方式导入它。

    代码
    // types/legacy-lib.d.ts
    declare module 'legacy-lib' {
      export function format(date: Date, pattern: string): string;
      export function parse(str: string, pattern: string): Date;
      export const VERSION: string;
      export type Format = 'short' | 'long' | 'iso';
    }
    
    // usage.ts
    import { format, parse, VERSION } from 'legacy-lib';
    const s: string = format(new Date(), 'YYYY-MM-DD'); // fully typed

    预期结果

    从 'legacy-lib' 的导入完全有类型,尽管 JS 中没有实际类型。

  2. 2

    声明全局变量

    使用 declare global 添加全局变量类型,例如为设置 window.config 的 script 标签。

  3. 3

    用自定义方法增强 String

    模块增强向现有类型添加内容。通过声明合并为 String 添加 reverse() 方法。谨慎使用 —— 它影响所有字符串。

  4. 4

    增强第三方模块

    例如向 Express Request 添加自定义属性。模块增强让你扩展你不拥有的类型。

  5. 5

    测试声明

    导入无类型模块并使用增强的类型。验证编译器捕获类型错误 —— 如果没有,说明你的声明太宽松了。

    代码
    // If format returns string, this should error:
    const n: number = format(new Date(), 'x'); // Error: string not assignable to number
    
    // Augmented method:
    const s: string = 'hello'.reverse(); // 'olleh' — typed as string

    预期结果

    误用声明类型时出现类型错误,确认它们工作正常。

自己动手试试

你学到了什么

你编写了声明文件 —— 让 TypeScript 使用整个 JavaScript 生态系统的桥梁。模块增强安全地扩展你不拥有的类型。

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

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

查看错误

← 返回主题