用 declare 为第三方库补充类型,.d.ts 不产生运行代码。

本节要点

  • declare module 声明模块
  • export 暴露类型
  • 适合无类型的旧库

代码示例

// types.d.ts
declare module "my-lib" {
  export function greet(name: string): string
  export const version: string
}

// 使用
import { greet } from "my-lib"
console.log(greet("TypeScript"))