1

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?

2
  • 1
    TypeScript is a superset of JavaScript, which means this code, which is valid JavaScript, is also valid TypeScript. Commented Apr 12, 2016 at 7:32
  • @Gothdo while that is true, TypeScript makes it a pain to extend objects after their types are defined because of the static typing. Like adding properties to a function. It's much easier and cleaner to transform the code to a class. :) Commented Apr 12, 2016 at 7:34

1 Answer 1

3

A TypeScript interface describing that code would be:

interface MainIf {
    (options) : string ; // the main function
    methodName() : any;
    propertyName: number;
    objectName: Object;
}
Sign up to request clarification or add additional context in comments.

9 Comments

indeed he doesn't, but it is cleaner this way. :) the alternative is to add type assertions to <any> when adding the extra properties on the main function. I'll make an example of that too. :)
I think there maybe some misunderstanding. I was asking for a declaration interface for an existing Node.js module, not for a way to implement a new class that works in the same way.
@vitaly-t I added another example that just patches the current code to have it work in the typescript compiler. The generated js code for the 2 should be equivalent.
@vitaly-t I did, does that fit?
@toskv in my module main(options) is a function that returns a string, it is not in any way a class. How to amend it then?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.