Sam Saint-Pettersen
Sam Saint-Pettersen

Reputation: 511

Exception with type definition for random-string module

I am trying to write a .d.ts for random-string.

I have this code:

declare module "random-string" {
    export function randomString(opts?: Object): string;
}

I am able to import the module no problem then with:

import randomString = require('random-string');

and invoke:

console.log(randomString); // --> [Function: randomString]

However, this doesn't work with or without an argument:

console.log(randomString({length: 10});
console.log(randomString());

I get this error from tsc:

error TS2088: Cannot invoke an expression whose type lacks a call signature.

I looked in the source for random-string and found this code for the method I am trying to interface with:

module.exports = function randomString(opts) {
   // Implementation...
};

I managed to write a .d.ts for the CSON module, no problem, but that was exporting a 'class' rather than a function directly. Is that significant?

Upvotes: 0

Views: 428

Answers (1)

Fenton
Fenton

Reputation: 250932

Your declaration says there is a module named random-string with a function named randomString within it...

So your usage should be:

console.log(randomString.randomString({ length: 10 }));
console.log(randomString.randomString());

If the module does actually supply the function directly, you should adjust your definition to do the same:

declare module "random-string" {
    function randomString(opts?: Object): string;

    export = randomString;
}

This would allow you to call it as you do in your question.

Upvotes: 1

Related Questions