How to use Interface In Typescript
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.
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"
}
}
}
How to Create Self-Referencing Objects in TypeScript ?
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.
Table of Content
- Using Interface
- Using Class
- Using Functional Approach