如何为具有构造函数的外部commonjs模块编写TypeScript声明文件? [英] How do I write a TypeScript declaration file for an external commonjs module that has constructor?
问题描述
请参阅更多详细问题:如何为具有构造函数(例如imap)的复杂外部commonjs模块编写TypeScript声明文件?
PLEASE SEE MORE DETAILED QUESTION: How do I write a TypeScript declaration file for a complex external commonjs module that has constructor, such as imap?
我为一个Node.js应用程序,我想为一个在模块级别具有构造函数的javascript模块(可从npm获取)编写TypeScript声明文件。
I write TypeScript for a Node.js app, and I want to write a TypeScript declaration file for a javascript module (available from npm) that has a constructor at the module level.
这里是相关代码的简化版本,位于文件 a.js 中:
Here is a simplified version of the relevant code, in file a.js:
function A(config) {
this.state = 'constructed';
}
A.prototype.update = function() {
this.state = 'updated';
};
module.exports = A;
和一个简化的JavaScript应用程序 app.js ,该模块使用 a :
and a simplified javascript application, app.js, that uses module 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声明文件?
How do I write a TypeScript declaration file for module a.js?
我已阅读用于编写定义(.d.ts)文件的TypeScript指南
,但不幸的是,我不知道如何将准则应用于这种情况。
I've read the TypeScript Guide for Writing Definition (.d.ts) Files but unfortunately, I couldn't figure out how to apply the guidelines to this case.
这是我的声明文件 adts :
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应用程序。
我也想将它们保留在模块中,以免Config之类的名称与其他模块中的名称冲突。
I can't figure out how to make the interfaces available to my TypeScript app. I also want to keep them within the module, so that names like Config don't collide with those from other modules.
我希望我的 app.ts 看起来像这样:
This is what I expect my app.ts to look like:
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)
推荐答案
有几种方法可以做到这一点,
There are a couple ways to do this, here is one:
declare class A {
state: string;
constructor(config: any);
update(): void;
}
declare module 'a' {
var out: typeof A;
export = out;
}
编辑:如果您要包含接口,但又要有一个导出的类,您可以这样设置:
If you want to include interfaces, but also have an exported class, you can set it up like this:
declare module A {
class A {
state: string;
constructor();
update(): void;
}
interface B {
value: any;
}
}
declare module 'a' {
var out: typeof A.A;
export = out;
}
这篇关于如何为具有构造函数的外部commonjs模块编写TypeScript声明文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!