How to Create Self-Referencing Objects in TypeScript ?
Last Updated :
06 May, 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"
}
}
}
Using Functional Approach
In this approach, we leverage TypeScript's functional programming capabilities to create self-referencing objects. We define a function to recursively construct the nodes of the linked list, forming the self-referencing structure.
Syntax:
type LinkedListNode = {
data: string;
next?: LinkedListNode;
};
const createNode = (data: string, next?: LinkedListNode): LinkedListNode => ({
data,
next,
});
const constructLinkedList = (dataArray: string[]): LinkedListNode | undefined => {
if (dataArray.length === 0) return;
const [firstData, ...restData] = dataArray;
return createNode(firstData, constructLinkedList(restData));
};
Example: In this example we defines a LinkedListNode type for a linked list, creates nodes, and constructs a linked list from an array, logging it.
JavaScript
type LinkedListNode = {
data: string;
next?: LinkedListNode;
};
const createNode = (data: string, next?: LinkedListNode): LinkedListNode => ({
data,
next,
});
const constructLinkedList = (dataArray: string[]): LinkedListNode | undefined => {
if (dataArray.length === 0) return;
const [firstData, ...restData] = dataArray;
return createNode(firstData, constructLinkedList(restData));
};
const linkedList = constructLinkedList(["Geeks", "for", "Geeks"]);
console.log(linkedList);
Output:
{
"data": "Geeks",
"next": {
"data": "for",
"next": {
"data": "Geeks",
"next": undefined
}
}
}
Similar Reads
How to Create Interface with Self-Reference Property in TypeScript ?
In TypeScript, interfaces allow you to define the structure of objects. Sometimes, you may need to create interfaces where an object property refers to the object itself. This is useful for defining recursive data structures like trees or linked lists. Table of Content Direct Reference ApproachUsing
2 min read
How to Create an Object in TypeScript?
TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do.Table of ContentUsing JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsing
5 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility.Below are the approaches used to sort or redu
3 min read
How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below.Table of ContentUsing th
3 min read
How to Iterate Array of Objects in TypeScript ?
In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows:Table of ContentUsing for...o
3 min read
How to Create Objects with Dynamic Keys in TypeScript ?
In TypeScript, objects with dynamic keys are those where the key names are not fixed and can be dynamically determined at runtime. This allows the creation of flexible data structures where properties can be added or accessed using variables, providing more versatile type definitions.These are the f
3 min read
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
5 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
3 min read
How to add TypeScript in Next.js ?
In this article, we will learn how to add TypeScript in Next.js.Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in t
5 min read