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 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 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
4 min read
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 classBy using the namespacesBy using the modulesBy defining
3 min read
How to Cast Object to Interface in TypeScript ? In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
3 min read
Syntax to create function overloading in TypeScript Function overloading is a feature in object-oriented programming where multiple functions can have the same name but different parameters. The parameters can differ in number, types, or both. This allows a single function name to perform different tasks based on the input parameters.Syntax: function
2 min read
How to Setup a TypeScript Project? In the world of modern web development, TypeScript has emerged as a powerful superset of JavaScript, offering static typing and improved tooling. Its strong typing system helps developers catch errors early during development, leading to more maintainable and scalable code. Whether you're starting a
2 min read
How to define Singleton in TypeScript? In this article, we will learn about the Singleton in TypeScript. A singleton is a class that always has only one instance of it at the global level. If more than one instance is created then they all will refer to the same instance and changes in the properties of one instance will reflect in the p
3 min read