vitaly-t
vitaly-t

Reputation: 25840

Declaring JavaScript extended functions in TypeScript

I have this type of Node.js module written in JavaScript:

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?

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.

UPDATE

Following suggestion from @toskv, I have added the following interface:

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..

Any idea why?

Upvotes: 1

Views: 66

Answers (1)

toskv
toskv

Reputation: 31600

A TypeScript interface describing that code would be:

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

Upvotes: 3

Related Questions