P Varga
P Varga

Reputation: 20219

function as ambient module in TypeScript

How do I declare an ambient module that is a function?

declare module "UUID" {
  (seed?: number): string;
}

↑ Doesn't work.

Upvotes: 3

Views: 143

Answers (4)

binki
binki

Reputation: 8308

Actually, for some reason, exporting a function directly as other answers here suggest seems to fail for me. Inside of declare module, I found I had to declare

  1. A callable interface
  2. A variable of that interface’s type

Then I could export the variable. For example, this should work (names changed, please comment if I have typos):

declare module 'UUID' {
  interface UuidFunc {
    (seed?: number): string;
  }
  const uuid:UuidFunc;
  exports = uuid;
}

Error

If I try the advice of the other answers, namely:

declare module 'UUID' {
  function uuid(seed?:number):string;
  export = uuid;
}

and try to consume it with this code, I then get an error:

// TS2497: Module ''UUID'' resolves to a non-module entity and cannot be imported using this construct
import * as uuid from 'UUID';

Upvotes: 0

Jonas Berlin
Jonas Berlin

Reputation: 3482

Derived from mk.'s answer, I had to arrange things a bit differently to make my compiler happy:

declare module 'UUID' {
  namespace UUID {
    // ...
  }

  function UUID(seed?: number): string;

  export = UUID;
}

I must say it looks (a bit) more sane to me as well :)

Upvotes: 0

mk.
mk.

Reputation: 11710

You can also use declaration merging, if you need to specify properties on your function.

declare module UUID {
    // ...
};
declare function UUID(seed?: number): string;

declare module "UUID" {
    export = UUID;
}

None of this is recommended, but is inevitable when converting old js.

Upvotes: 3

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220914

declare module "UUID" {
    function uuid(seed?: number): string;
    export = uuid;
}

This is some text because code-only answers get flagged for attention!

Upvotes: 2

Related Questions