node.js - 如何为具有构造函数的外部 commonjs 模块编写 TypeScript 声明文件?

标签 node.js typescript declaration commonjs

请查看更详细的问题:How do I write a TypeScript declaration file for a complex external commonjs module that has constructor, such as imap?

我为 Node.js 应用编写 TypeScript,我想为在模块级别具有构造函数的 javascript 模块(可从 npm 获得)编写 TypeScript 声明文件。

这是相关代码的简化版本,在文件 a.js 中:

function A(config) {
    this.state = 'constructed';
}
A.prototype.update = function() {
    this.state = 'updated';
};
module.exports = A;

和一个简化的 javascript 应用程序 app.js,它使用模块 a:

var mod = require('a');
var i = new mod({});
console.log('i.state=' + i.state);
i.update();
console.log('i.state=' + i.state);

如何为模块 a.js 编写 TypeScript 声明文件?

我读过 TypeScript Guide for Writing Definition (.d.ts) Files 但不幸的是,我不知道如何将指南应用到这个案例中。


已更新以包含接口(interface)

这是我的声明文件a.d.ts:

declare module 'a' {
    import events                           = require('events');
    import EventEmitter                     = events.EventEmitter;

    interface Config {
        foo: number;
    }
    interface Other {
        baz: number;
    }

    class A extends EventEmitter {
        state: string;
        constructor(config: Config);
        update(): void;
    }

    var out: typeof A;
    export = out;
}

我不知道如何让我的 TypeScript 应用程序可以使用这些接口(interface)。 我还想将它们保留在模块中,这样像 Config 这样的名称就不会与其他模块中的名称冲突。


添加了使用此声明的 TypeScript 应用

我希望我的 app.ts 看起来像这样:

import mod = require('a');
import Config = mod.Config;
import Other = mod.Other;

var other : Other = {a: 2};
var config : Config = {foo: 2};
var i = new mod(config);
console.log('i.state=' + i.state)
i.update();
console.log('i.state=' + i.state)

最佳答案

有几种方法可以做到这一点,这里是一种:

declare class A {
    state: string;
    constructor(config: any);
    update(): void;
}

declare module 'a' {
    var out: typeof A;

    export = out;
}

编辑:如果你想包含接口(interface),但也有一个导出类,你可以这样设置:

declare module A {
    class A {
        state: string;
        constructor();
        update(): void;
    }

    interface B {
        value: any;
    }
}

declare module 'a' {
    var out: typeof A.A;

    export = out;
}

关于node.js - 如何为具有构造函数的外部 commonjs 模块编写 TypeScript 声明文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242880/

相关文章:

node.js - 使用npm安装包时无法读取未定义的属性 'resolve'

javascript - Typescript 定义 Breeze.d.ts - 环境上下文中已经存在的代码不允许声明修饰符

objective-c - 在 switch 语句中声明变量

java - 在 if/else block 中声明变量

c - 在全局范围内混合使用 extern、static 和无存储说明符的声明

php - 为什么在 laravel 中使用 npm?

node.js - 从 nodejs 的 nodemailer 发送电子邮件

javascript - req.ip 可以在 Express.js 中伪造吗?

dependency-injection - Angular 2 - 将依赖项注入(inject)装饰器工厂

javascript - 函数链不工作 Angular 5