Can you create nested classes in TypeScript?

后端 未结 4 981
情歌与酒
情歌与酒 2020-12-08 03:49

Is there a way to nest classes in TypeScript. E.g. I\'d like to use them like:

var foo = new Foo();
var bar = new Foo.Bar();
相关标签:
4条回答
  • 2020-12-08 04:06

    If you're in the context of a type declaration file, you can do this by mixing classes and namespaces:

    // foo.d.ts
    declare class Foo {
      constructor();
      fooMethod(): any;
    }
    
    declare namespace Foo {
      class Bar {
        constructor();
        barMethod(): any;
      }
    }
    
    // ...elsewhere
    const foo = new Foo();
    const bar = new Foo.Bar();
    
    0 讨论(0)
  • 2020-12-08 04:11

    Starting with TypeScript 1.6 we have class expressions (reference).

    This means you can do the following :

    class Foo {
        static Bar = class {
    
        }
    }
    
    // works!
    var foo = new Foo();
    var bar = new Foo.Bar();
    
    0 讨论(0)
  • Here is a more complex use case using class expressions.

    It allows the inner class to access the private members of the outer class.

    class classX { 
        private y: number = 0; 
    
        public getY(): number { return this.y; }
    
        public utilities = new class {
            constructor(public superThis: classX) {
            }
            public testSetOuterPrivate(target: number) {
                this.superThis.y = target;
            }
        }(this);    
    }
    
    const x1: classX = new classX();
    alert(x1.getY());
    
    x1.utilities.testSetOuterPrivate(4);
    alert(x1.getY());
    

    codepen

    0 讨论(0)
  • 2020-12-08 04:25

    I couldn't get this to work with exported classes without receiving a compile error, instead I used namespaces:

    namespace MyNamespace {
        export class Foo { }
    }
    
    namespace MyNamespace.Foo {
        export class Bar { }
    }
    
    0 讨论(0)
提交回复
热议问题