How do I write a TypeScript declaration file for an external commonjs module that has constructor?

☆樱花仙子☆ 提交于 2019-12-03 15:39:47

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;
}

EDIT: 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;
}

I found an existing declaration file for a modules that has similar structure to the one for which I want to write a declaration file: auth0

I now have something that works, although not yet ideal. The declaration file a.d.ts is:

/// <reference path='node.d.ts' />
interface Config {
    foo: number;
}

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

    class A extends EventEmitter {
        constructor(config : Config);
        state: string;
        update(): void;
    }
    var out: typeof A;
    export = out;
}

with the TypeScript app file app.ts being:

/// <reference path='a.d.ts' />
import mod = require('a');

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

and the a.js module being as in the original question.

I compile this with: tsc --module commonjs app.ts

This certainly works for now.

Although I think it's messy to have the interface (Config) outside of the module, but I haven't yet figured out how to move the interfaces inside.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!