Store reference to namespace instead of type

时间:2018-11-16 02:29:06

标签: tsc typescript3.0

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).

1 个答案:

答案 0 :(得分:1)

我像这样尝试过,并且有效

    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