Categories
TypeScript Answers

How to declare a nested class structure in TypeScript?

Spread the love

Sometimes, we want to declare a nested class structure in TypeScript.

In this article, we’ll look at how to declare a nested class structure in TypeScript.

How to declare a nested class structure in TypeScript?

To declare a nested class structure in TypeScript, we can create a namespace or module and put our class in it.

For instance, we write

class Outer {}

namespace Outer {
  export class Mid {}

  export module Mid {
    export class Inner {}
  }
}

const a = new Outer();
const b = new Outer.Mid();
const x = new Outer.Mid.Inner();

to create the Outer namespace.

And we put the Mid class in it.

Then we create the Mid module in the same namespace and put the Inner class in it.

Then we can access the 3 classes as we did in the last 3 lines.

Anything before the class name is the namespace or module name.

Conclusion

To declare a nested class structure in TypeScript, we can create a namespace or module and put our class in it.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.