By defining nested classes inside a class

In this approach, we will directly define the nested class inside the outer class.

Syntax:

class OuterClass{
static InnerClass = class{
}
}

Example: The below code example defines a nested class inside another class.

Javascript




class OuterClass {
    outerClassProperty: string;
 
    constructor(outerClassProperty: string) {
        this.outerClassProperty = outerClassProperty;
    }
 
    outerClassMethod() {
        console.log
            (`Outer Class property:
            ${this.outerClassProperty}`);
    }
 
    // Nested class
    static InnerClass = class {
        innerClassProperty: string;
 
        constructor(innerClassProperty: string) {
            this.innerClassProperty = innerClassProperty;
        }
 
        innerClassMethod() {
            console.log
                (`Inner Class property:
                ${this.innerClassProperty}`);
        }
    }
}
const outerClassInstance = new OuterClass("w3wiki");
outerClassInstance.outerClassMethod();
const innerClassInstance =
    new OuterClass.InnerClass("A Computer Science Portal");
innerClassInstance.innerClassMethod();


Output:

Outer Class property: w3wiki
Inner Class property: A Computer Science Portal

How to Create Nested Classes in TypeScript ?

In TypeScript, you can create nested classes using different methods. We will discuss about three different approaches to creating nested classes in TypeScript.

These are the approaches:

Table of Content

  • By defining nested classes inside a class
  • By using the namespaces
  • By using the modules

Similar Reads

By defining nested classes inside a class

In this approach, we will directly define the nested class inside the outer class....

By using the namespaces

...

By using the modules

The namespace can also be used to create a namespace of Outer class and the namespace of the inner class which can be later merged together to create nested classes....