Open In App

How to Create Interface with Self-Reference Property in TypeScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Direct Reference Approach

In the Direct Reference approach, the interface directly references itself within its definition. This straightforward method allows for clear and explicit declaration of recursive data structures in TypeScript.

Syntax:

interface TreeNode {
value: number;
left?: TreeNode;
right?: TreeNode;
}

Example: The below code creates an interface with self referencing property to create a TreeNode.

Javascript




interface TreeNode {
    value: number;
    left?: TreeNode;
    right?: TreeNode;
}
 
const rootNode: TreeNode = {
    value: 5,
    left: {
        value: 3,
        left: { value: 2 },
        right: { value: 4 }
    },
    right: {
        value: 8,
        left: { value: 7 },
        right: { value: 9 }
    }
};
 
console.log(rootNode);


Output:

{
value: 5,
left: {
value: 3,
left: {
value: 2
},
right: {
value: 4
}
},
right: {
value: 8,
left: {
value: 7
},
right: {
value: 9
}
}
}

Using Type Aliases Approach

Using the Type Aliases approach employs the type keyword to create a type alias that references itself. This technique offers an alternative to interface declarations and provides flexibility in defining recursive data structures.

Syntax:

type TreeNode = {
value: number;
left?: TreeNode;
right?: TreeNode;
}

Example: The below code implements the Type Alias to create an interface with self referencing property.

Javascript




type TreeNode = {
    value: number;
    left?: TreeNode;
    right?: TreeNode;
}
 
const rootNode: TreeNode = {
    value: 5,
    left: {
        value: 3,
        left: { value: 2 },
        right: { value: 4 }
    },
    right: {
        value: 8,
        left: { value: 7 },
        right: { value: 9 }
    }
};
 
console.log(rootNode);


Output:

{
value: 5,
left: {
value: 3,
left: {
value: 2
},
right: {
value: 4
}
},
right: {
value: 8,
left: {
value: 7
},
right: {
value: 9
}
}
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads