Typescript: namespaces with the same name compile without problem?

Created on 15 Nov 2018  路  5Comments  路  Source: microsoft/TypeScript

I have this file:

export namespace Entities {

  export namespace Foo {

  }

  export namespace Foo {

  }


}

it compiles without error to:

export declare namespace Entities {
    namespace Foo {
    }
    namespace Foo {
    }
}

I would assume there would be a class of names? Foo clashing with Foo? I don't get it. I am on tsc v3.1.6

Question

Most helpful comment

See:

export namespace Entities {

  export namespace Foo {
    export var a = 0; // var a
  }

  export namespace Foo {
    export var b = 0; // var b
  }
}

Is converted to (into playground):

define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Entities;
    (function (Entities) {
        var Foo;
        (function (Foo) {
            Foo.a = 0; // var a
        })(Foo = Entities.Foo || (Entities.Foo = {}));
        (function (Foo) {
            Foo.b = 0; // var b
        })(Foo = Entities.Foo || (Entities.Foo = {}));
    })(Entities = exports.Entities || (exports.Entities = {}));
});

Playground.

All 5 comments

See:

export namespace Entities {

  export namespace Foo {
    export var a = 0; // var a
  }

  export namespace Foo {
    export var b = 0; // var b
  }
}

Is converted to (into playground):

define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Entities;
    (function (Entities) {
        var Foo;
        (function (Foo) {
            Foo.a = 0; // var a
        })(Foo = Entities.Foo || (Entities.Foo = {}));
        (function (Foo) {
            Foo.b = 0; // var b
        })(Foo = Entities.Foo || (Entities.Foo = {}));
    })(Entities = exports.Entities || (exports.Entities = {}));
});

Playground.

Namespaces with the same name merge and have the same scope - that's what makes them namespaces.

@weswigham is there a purpose for that? Seems like it should just throw an error? I am looking for an error to prevent duplicate declarations.

Yeah... The purpose is to be able to split a single namespace across multiple files. Namespaces in other languages typically work in a similar fashion.

Tbh, for most modern TS codebases, we'd advise people develop with modules rather than namespaces, since that's JS standard.

got it thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tenry92 picture tenry92  路  146Comments

disshishkov picture disshishkov  路  224Comments

fdecampredon picture fdecampredon  路  358Comments

yortus picture yortus  路  157Comments

Gaelan picture Gaelan  路  231Comments