Search code examples
angulartypescripthierarchynaming

typescript class and namescript hierarchy when do importing


I have a question about name conflict but didn't cause any errors and seems to export pre usual to the outside scope. Best way to show is in this simplify code;

Endpoints.model.ts

namespace Endpoints {
 export class FruitWorld {
  apple: string;
  banana: string;
  seller: string;
  sellerId: string;
  get produceDate() {
   ...
  }
 }
}
export class FruitWorld extended Endpoints.FruitWorld {
 Seller: string;
 SellerId: string;
 get ProduceDate() {
  ...
 }
 constructor(...init: Partial<Endpoints.FruitWorld>[]) {
  super();
  init.map(data => {
   delete data.Apple;
   delete data.Banana;
   Object.assign(this, data);
  }
 }
}
export namespace FruitWorld {
 // Some overwrite function 
 // extended functionalities
}

app.ts

import { FruitWorld } "./Endpoints.model";

Here is the confusing part, which one of the FruitWorld is being imported here? From what I can tell, it is the class get imported.

I read this stackover question and this stackover question, but they are not really touching on what if we have a class and a namespace share same name, and exists in the same file. Which gets export?


Solution

  • Class export will be overridden by a namespace if a namespace is non-empty:

    export class Foo { }
    
    export namespace Foo {
        let bar;
    }
    

    So it persists in compiler output:

    var Foo = /** @class */ (function () {
        function Foo() {
        }
        return Foo;
    }());
    exports.Foo = Foo;
    (function (Foo) {
        var bar;
    })(Foo = exports.Foo || (exports.Foo = {}));
    exports.Foo = Foo;
    

    And class export won't be overridden by a namespace if it's empty:

    export class Foo { }
    
    export namespace Foo {
        // let bar;
    }
    

    So it's removed from compiler output:

    var Foo = /** @class */ (function () {
        function Foo() {
        }
        return Foo;
    }());
    exports.Foo = Foo;