为类指定构造函数参数

时间:2019-04-06 19:48:50

标签: typescript typescript-typings

我在经典的ES6 npm包中有一个这样的ES6类:

class Document {
  /**
   *
   * @param {Object} options
   * @param {String} [options.title]
   * @param {String} [options.type]
   * @param {String} [options.detail]
   * @param {String} [options.instance]
   * @param {Number} [options.status]
   * @param {Extension} [extension]
   */
  constructor (options, extension) { // some implementation ... }
}

现在,我想为该类提供一些TypeScript类型。

我尝试了此操作,但是optionsextension被例如WebStorm或VS代码。

declare module "myModule" {

    class Document implements IDocument {
        constructor(options: IDocumentOptions, extension: IExtension)

        detail: string;
        extension: IExtension;
        instance: string;
        status: number;
        title: string;
        type: string;
    }

    interface IDocument {
        title: string,
        type: string,
        detail?: string,
        instance?: string,
        status: number,
        extension?: IExtension
    }

    interface IDocumentOptions {
        title: string,
        type: string,
        detail?: string,
        instance?: string,
        status: number,
        extension?: IExtension
    }

    interface IExtension {

    }

    const _: {
        Document: Document
    }


    export = _;

    }
};

2 个答案:

答案 0 :(得分:0)

我猜您正在尝试覆盖现有的Document变量。

declare var Document: {
    prototype: Document;
    new(): Document;
};

只需重命名类并添加构造函数实现,最后它就应该起作用

答案 1 :(得分:0)

解决了:

type DocumentConstructor = 
    new (options: IDocumentOptions, extension: IExtension) => IDocument;

代替

class Document implements IDocument {
    constructor(options: IDocumentOptions, extension: IExtension)

    detail: string;
    extension: IExtension;
    instance: string;
    status: number;
    title: string;
    type: string;
}