Definitelytyped: How to create a type definition for a CommonJS module that exports a function?

Created on 1 Nov 2016  路  6Comments  路  Source: DefinitelyTyped/DefinitelyTyped

I'm trying to contribute a type definition for a module that exports like this:

  module.exports = function (store) {
    return store;
  };

But using export = or export default gave me all sort of errors.

What is the best of exporting for modules like this today?

Most helpful comment

function foo(store:any): void;
declare namespace foo {}
export = foo;
import * as fn from 'foo';

http://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html

All 6 comments

function foo(store:any): void;
export = foo;

try this form.

@vvakame without declaring any module?

let's say that file that is exporting function is at node_modules/foo/index.js

and I'm putting my .d.ts file in node_modules/@types/foo/index.d.ts

If content of index.d.ts is the following, it won't work:

dclare module 'foo' {
function foo(store:any): void;
export = foo;
}

When I import "foo", I get following error:

import fn from 'foo';
 error TS2497: Module ''foo'' resolves to a non-module entity and cannot be imported using this construct.
function foo(store:any): void;
declare namespace foo {}
export = foo;
import * as fn from 'foo';

http://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html

That's not working either. It's the same problem as https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11720

if a npm module is exporting a function, there is that problem...

@mhegazy what you recommend?

The error message is correct: "foo" is a non-module entity -- a function. It should be imported as import foo = require("foo"). And @vvakame is correct that you shouldn't need the declare module "foo" wrapper, since the location of the types (node_modules/@types/foo/index.d.ts) already determines the module being declared.

Was this page helpful?
0 / 5 - 0 ratings