You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为包含多模块/类的复杂原生JavaScript库编写可用的.d.ts声明文件

核心错误原因

你当前的类型声明写法不符合库的实际导出结构:嵌套的declare module是用来声明路径子模块(即import 'library-name/xxx'这类导入形式)的,而你的库所有模块/类都是直接挂载在根模块导出的对象上,不需要嵌套声明。

正确的类型声明写法

declare module 'library-name' {
  // 替换为你实际用到的类型定义
  type SomeType = string;
  type FunctionType = (param: SomeType) => number;

  // 普通函数模块声明
  export const module1: {
    functionName: FunctionType;
  };

  // 可实例化的类模块声明
  export class class_module {
    function1(parameter: SomeType): FunctionType;
    function2(): void;
  }

  // IIFE导出的类声明
  export class ClassName {
    // 补齐类的所有方法、属性定义
    methodA(): void;
    propB: number;
  }
}

正确使用示例

CommonJS 导入(和你原有写法兼容)

const lib = require('library-name');

// 普通模块调用
lib.module1.functionName('test');

// 类实例化+类型标注
const instance: lib.class_module = new lib.class_module();
instance.function1('test');
instance.function2();

// IIFE导出的类使用
const clsInstance: lib.ClassName = new lib.ClassName();
clsInstance.methodA();

ES模块导入(可选)

如果要使用import语法,需要先在tsconfig.json中开启esModuleInterop: true,之后可以这么写:

import { module1, class_module, ClassName } from 'library-name';

const instance: class_module = new class_module();

原有报错的解释

  1. "'class_module' refers to a value, but is being used as a type here":你之前把类写在嵌套的declare module内,导出的class_module是一个模块对象,只能拿到其默认导出的构造值,无法直接将模块名作为类型使用。
  2. "This expression is not callable. Type 'typeof ObjectName' has no call signatures":你之前对IIFE导出的类声明有误,没有将其声明为可实例化的class类型,而是被TS识别为普通对象,因此没有构造签名也找不到对应方法。

导出方式对类型声明的影响

不同的模块导出方式确实会影响类型声明的编写:

  • 用module.exports = xxx全量导出的模块,类型声明需要用export = xxx匹配
  • 用exports.xxx = xxx导出单个属性的模块,类型声明直接用export const xxx/export class xxx匹配
  • 用IIFE实现的UMD导出,本质和CommonJS导出逻辑一致,按照实际挂载到exports上的结构写声明即可,如果类同时被挂载到全局作用域,还需要额外补充全局类型声明。

内容的提问来源于stack exchange,提问作者GreatGooeyGoobers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:45:05