How to use Classes In Typescript

Classes in TypeScript are like blueprints for making objects. They define what properties and functions an object will have. With classes, we can also use generic type parameters, which means we can make a class that works with different types of data. When we make a class recursively generic, it means instances of the class can have properties that are references to other instances of the same class. This lets us build Data Structures like trees or linkedList.

Syntax:

class TreeNode<T> {
value: T;
children: TreeNode<T>[];
constructor(value: T) {
this.value = value;
this.children = [];
}
}

Example: This TypeScript code creates a class representing tree nodes with values and child nodes. It constructs a tree structure with numeric values, establishes parent-child relationships, and logs the root node to the console.

Javascript




class RecursiveTreeNode<T> {
    value: T;
    children?: RecursiveTreeNode<T>[];
 
    constructor(value: T) {
        this.value = value;
        this.children = [];
    }
}
 
const root = new RecursiveTreeNode < number > (1);
const child1 = new RecursiveTreeNode < number > (2);
const child2 = new RecursiveTreeNode < number > (3);
const grandchild = new RecursiveTreeNode < number > (4);
 
root.children.push(child1);
root.children.push(child2);
child1.children.push(grandchild);
 
console.log(root);


Output:

[LOG]: RecursiveTreeNode {
value: 1,
children: [
RecursiveTreeNode { value: 2, children: [ [RecursiveTreeNode] ] },
RecursiveTreeNode { value: 3, children: [] }
]
}


How to Implement Recursive Generics in TypeScript ?

In TypeScript, Recursive generics let you use generic types that refer to themselves inside their definition. This is helpful when we are working with nested or hierarchical Data Structures or Algorithms. Using this we can create flexible and reusable code for managing complex Data Structures. There are several approaches to implementing recursive generics in TypeScript which are as follows:

Table of Content

  • Using Interfaces
  • Using Type aliases
  • Using Classes

Similar Reads

Using Interfaces

In this approach, we define the structure of objects using TypeScript interfaces. Interfaces allow us to specify the shape of an object, including the names and types of its properties....

Using Type aliases

...

Using Classes

This TypeScript code defines a type named RecursiveTreeNode, representing a tree node with a value of type T and an optional array of child nodes of the same type....

Contact Us