This project is read-only.

Combined module and class supported?

Topics: General, Language Specification
Jun 24, 2013 at 3:46 PM
Currently, it is possible to create a module and a class with the same name:
module A {
    export class M {
        public g () {}
    export module M {
        export function f () {}
In the generated code, the module and the class will be the same object.

Is this behavior that is intended, and can we rely on it staying this way? Or might this be disallowed in the future, or generate two separate objects?
Jun 24, 2013 at 5:05 PM
It is allowed now, and it creates a hybrid of the two. You can read about this under "Declaration Merging" here
Jun 24, 2013 at 6:04 PM
Thanks! We're generating code that looks like this, in an effort to migrate from our previous class system to TypeScript. I wanted to make sure I wasn't building on quicksand.
Jun 24, 2013 at 6:16 PM
One strange thing I noticed: this works as long as you declare the class first, but not if you declare the module first (unless you don't export the module). Is this intended behavior as well?
Jun 24, 2013 at 7:28 PM
The intended behavior is that the class must be declared before the module. This is to ensure that the combined class/module object is created as a (constructor) function as JavaScript provides no way to add "functionness" to an already existing object. The topic is covered in detail in section 10.5 of the Language Specification.

It is entirely possible that the error messages produced by the compiler aren't as helpful as they could be in this area.
Jun 24, 2013 at 8:53 PM
The error currently just says Duplicate identifier, which indeed doesn't really help explain that it would be allowed if the order was swapped.
Jun 24, 2013 at 9:35 PM
Yeah we're aware that the error messages here aren't great. We hope to improve them over time but first we want to make sure that things written correctly always work :)
Jun 25, 2013 at 10:07 AM
Noble goal! Thanks again for all the hard work!