Module as function

Topics: General, Language Specification
Dec 19, 2013 at 3:44 PM
Edited Dec 19, 2013 at 3:47 PM
Since modules become types by typeof Module (what is good), impossible define a function with same name. It was possible to define like this:
declare module My {
  export class C { ... }
  export smth();
}
declare function My(x: number): My.C;

var c: My.C = My(10); //usage
But now it's incorrect. Meantime it's useful scenario in many existing JS libraries.
Is it possible to introduce defining call signatures for module itself?
declare module My {
  export class C { ... }
  export smth();
  (x: number): My.C;
}

var c: My.C = My(10); //usage
pleeease =)
Developer
Dec 19, 2013 at 7:24 PM
The concept in your first example is still allowed, you just have unrelated errors in it. This works:
declare module My {
    export class C { foo: string; }
    export function smth();
}
declare function My(x: number): My.C;

var c: My.C = My(10); //usage
console.log(c.foo);
The details for the rules are in section 10.5 Declaration Merging in the language specification.
Dec 19, 2013 at 10:00 PM
Yes, you right. I was wrong in my description. It works if only one function signature provided.
So, if I want create overloads of function, the error Duplicate identifier produced:
declare module My {
    export class C { foo: string; }
    export function smth();
}
declare function My(x: number): My.C;
declare function My(y: boolean): My.C; // fail
declare var My: { // this fail too
 ()L My.C;
 (x: number): My.C;
};
And it was worked in 0.9.1.
Developer
Dec 19, 2013 at 10:11 PM
Edited Dec 19, 2013 at 10:14 PM
Ah, I see. It looks like this works correctly as long as you put the function overloads before the module. This is normally required when writing non-ambient code but not necessary when writing ambient declarations. Hopefully that at least gives you a viable workaround until we fix this.

Also note that the version with a var of a function type has never worked and is not intended to.
Developer
Dec 19, 2013 at 10:13 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.
Dec 20, 2013 at 7:37 AM
@danquirk, thanks!
Actually the reason it was not work (Sammy library typings) is another. I filed the new bug.