3

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?

roger
  • 1,225
  • 2
  • 17
  • 33
  • Hmm, good question, best way to find out would be to try different attributes names in each `FruitWorld` class and see the one which is defined I guess ? – Sebastien Servouze May 16 '18 at 11:55
  • 1
    Hi @SebastienServouze I think the class inside the namespace `Endpoints` is not a problem here, because it is encapsulated by the namespace and it can only be used in the local file. My concern is the namespace and class share same name. – roger May 16 '18 at 12:05

1 Answers1

4

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;
Estus Flask
  • 206,104
  • 70
  • 425
  • 565