简体   繁体   English

在TypeScript中声明JavaScript扩展函数

[英]Declaring JavaScript extended functions in TypeScript

I have this type of Node.js module written in JavaScript: 我有这种用JavaScript编写的Node.js模块:

function main(options) {
    return "some string";
}

main.methodName = function () {
    // implementation;
};

main.objectName = {
    // a namespace;
};

main.propertyName = 123;

module.exports = main;

What is the proper way of declaring such an interface in TypeScript? 在TypeScript中声明这样的接口的正确方法是什么?

CLARIFICATION 澄清

I'm asking about how to properly declare such an interface in TypeScript for an existing Node.js module, so it can be used correctly from TypeScript files, not how to re-implement such interfaces in TypeScript. 我问的是如何在TypeScript中为现有的Node.js模块正确声明这样的接口,因此可以从TypeScript文件中正确使用它,而不是如何在TypeScript中重新实现这样的接口。

UPDATE UPDATE

Following suggestion from @toskv, I have added the following interface: 根据@toskv的建议,我添加了以下界面:

declare module "my-module" {

    // Default library interface
    interface main {
        (options?:{}):string,
        methodName():any,
        propertyName:any,
        objectName:Object
    }

    export default main;
}

But if I use it like this: 但如果我像这样使用它:

import * as myModule from "my-module";
var s = myModule({});

Then I'm getting error Cannot invoke an expression whose type lacks a call signature. 然后我收到错误Cannot invoke an expression whose type lacks a call signature. .

Any idea why? 知道为什么吗?

A TypeScript interface describing that code would be: 描述该代码的TypeScript接口将是:

interface MainIf {
    (options) : string ; // the main function
    methodName() : any;
    propertyName: number;
    objectName: Object;
}

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

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