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?
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.
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.
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.
A inner class declared in the same outer class (or in its descendant) can inherit another inner class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With