繁体   English   中英

如何为 NPM package 原型 object 声明环境 typescript class?

[英]How to declare ambient typescript class for an NPM package prototype object?

我有一个 NPM package 有一个 object 如下:

const Lipsum = function constructor(argOne, argTwo) {
...
}

Object.assign(Lipsum.prototype, {
    firstMethod: function firstMethod(firstArg, secondArg){...}
    secondMethod: function secondMethod(){}
})

module.exports = Lipsum;

我想为它声明一个环境 TypeScript class。 我在我的项目shared/lipsum.d.ts中创建了一个文件并编写了以下内容:

declare class Lipsum {
    constructor(argOne: string, argTwo: number)

    firstMethod(firstArg: string, secondArg: string): string
    secondMethod(): void
}

export default Lipsum;

我面临以下问题:

const x = new Lipsum(); // <--- this doesn't throw an error, even though the constructor must have two arguments.
x. // <--- It doesn't autocomplete here, but it autocompletes above when I put a dot after "Lipsum()".

更新:

我试图用模块声明包装 class,如下所示:

declare module 'lipsum'{
    export default class Lipsum {
        constructor(argOne: string, argTwo: number)

        firstMethod(firstArg: string, secondArg: string): string
        secondMethod(): void
    }
}

它一直告诉我:

扩充中的模块名称无效。 模块“lipsum”解析为位于“/Users/yaharga/project/node_modules/lipsum/lipsum.js”的无类型模块,无法扩充。

我应该注意到代码已经在文件“lipsum.d.ts”中。

结果所有导入都需要在“声明模块”scope 内。感谢@drag13为我指明了正确的方向。

有关我收到的错误的更多信息,我使用这篇文章作为参考。

您需要指定与您的输入相关的模块。 只需像这里一样添加模块定义

declare module 'MODULE_NAME' {
   class Lipsum {
        constructor(argOne: string, argTwo: number)

        firstMethod(firstArg: string, secondArg: string): string
        secondMethod(): void
    }

    export default Lipsum;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM