Search code examples
tsctypescript3.0

Store reference to namespace instead of type


Say I have a namespace like so:

export namespace Foo1 {
  export namespace Foo2 {
    export namespace Foo3 {
      export interface Foo4 {}
      export interface Foo5 {}
    }
  }
}

in a .ts file I have something like this:

import {Foo1} from './foo';

const bar1 = function(){
   type t = Foo1.Foo2.Foo3.Foo4;
}

const bar2 = function(){
   type t = Foo1.Foo2.Foo3.Foo5;
}

this can get kinda verbose, I am looking to do something like this instead:

import {Foo1} from './foo';

type Foo3 = Foo1.Foo2.Foo3;  // <<< this don't work, I get an error explained below

const bar1 = function(){
   type t = Foo3.Foo4;
}

const bar2 = function(){
   type t = Foo3.Foo5;
}

but I can't seem to store a reference to a namespace, I can only store a reference to a type? (The error I get is that namespace Foo2 has no exported member Foo3).


Solution

  • I tried it like this and it works

        namespace Shapes {
        export namespace Polygons {
            export namespace Square {
                export interface Foo4 {}
    
            }
    
            export namespace Triangle {
                export interface Foo5 {}
            }
        }
    }
    
    
    import polygons = Shapes.Polygons;
    
    type myType = polygons.Square.Foo4;
    
    export class myClass implements polygons.Square.Foo4{
        myFoo4 = 'Foo4';
    
    }
    
    
    const myFooInstance = new myClass();
    
    console.log(myFooInstance.myFoo4);
    

    enter image description here