【问题标题】:How to declare ambient typescript class for an NPM package prototype object?如何为 NPM 包原型对象声明环境 typescript 类?
【发布时间】:2020-06-08 04:00:21
【问题描述】:

我有一个 NPM 包,其对象如下:

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

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

module.exports = Lipsum;

我想为它声明一个环境 TypeScript 类。我在我的项目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()".

更新:

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

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' 中了。

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

有关我收到的错误的更多信息,我使用了this post 作为参考。

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

    declare module 'MODULE_NAME' {
       class Lipsum {
            constructor(argOne: string, argTwo: number)
    
            firstMethod(firstArg: string, secondArg: string): string
            secondMethod(): void
        }
    
        export default Lipsum;
    }
    
    

    【讨论】:

    • 它一直告诉我扩展中的模块名称无效。模块“lipsum”解析为“/Users/jondoe/project/node_modules/lipsum/lipsum.js”处的无类型模块,无法扩充。
    • 很高兴看到您找到了解决方案。
    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2019-01-15
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2017-10-01
    相关资源
    最近更新 更多