Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing inner classes in typescript

I can successfully declare a nested class like this:

class Outer {
    static Inner = class Inner {

    };
}

However, I would like my outer class to hold some instances of my inner class:

class Outer {
    constructor() {
        this.inners = [new Outer.Inner()];
    }
    static Inner = class Inner {

    };

    inners: Array<Inner>; // this line errors
}

But this gives me error TS2304: Cannot find name 'Inner'.

How can I make this work?

like image 237
Eric Avatar asked Oct 01 '16 14:10

Eric


People also ask

How do you use class inside class in TypeScript?

To create nested classes in TypeScript, we can create a static class property in our class. class Foo { static Bar = class {}; } const foo = new Foo(); const bar = new Foo. Bar(); to create the Foo class that has the static Bar property which is set to a class expression.

Does TypeScript support nested classes?

Is it possible to define nested/inner class in typescript? Yes, it is. Go to chapter 3 or 4 if you want to know only nested/inner class.

How do you find the value of an inner class?

Accessing the Private Members Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.

Can we inherit inner class?

A inner class declared in the same outer class (or in its descendant) can inherit another inner class.


1 Answers

Not sure this can be achieved this way however, as a workaround:

class Outer {
    inners: Array<Outer.Inner>;
}

namespace Outer {
    export class Inner {
    }
}

Note: the class must be defined before the namespace

See it in action

like image 103
Bruno Grieder Avatar answered Oct 20 '22 20:10

Bruno Grieder