How to Create Self-Referencing Objects in TypeScript ?
Last Updated :
27 Feb, 2024
In TypeScript, self-referencing objects are mainly objects that have a relationship between the elements and the data structure. We can consider this as the Linked List Data Structure.
We can define the interface or the classes with the properties that may reference instances of the same type.
Using Interface
In this approach, we are going to use a TypeScript interface named node to define the structure of a self-referencing object. Each instance of the interface represents a node with a data property and an optional next property referencing another node.
Syntax:
interface node {
data: string;
next?: node;
}
Example: The below example uses Interface to create self-referencing objects in TypeScript.
Javascript
interface node {
data: string;
next?: node;
}
const node1: node =
{ data: "Geeks" };
const node2: node =
{ data: "for" , next: node1 };
const node3: node =
{ data: "Geeks" , next: node2 };
console.log(node3);
|
Output:
{
"data": "Geeks",
"next": {
"data": "for",
"next": {
"data": "Geeks"
}
}
}
Using Class
In this approach, we are using a TypeScript class named “node” to define a node structure for a linked list (self-referencing). The class includes a constructor to initialize the “data” and “next” properties, allows the creation of interconnected nodes, and the instantiation of instances forms a linked list.
Syntax:
class ClassName {
property1: type;
constructor(parameter1: type) {
this.property1 = parameter1;
}
methodName() {
// Method implementation
}
}
Example: The below example uses Class to create self-referencing objects in TypeScript.
Javascript
class node {
data: string;
next?: node;
constructor(data: string, next?: node) {
this .data = data;
this .next = next;
}
}
const node1 =
new node( "Geeks" );
const node2 =
new node( "for" , node1);
const node3 =
new node( "Geeks" , node2);
console.log(node3);
|
Output:
{
"data": "Geeks",
"next": {
"data": "for",
"next": {
"data": "Geeks"
}
}
}
Share your thoughts in the comments
Please Login to comment...