Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
What are TypeScript Interfaces?
Next article icon

What are Recursive Types & Interfaces in TypeScript ?

Last Updated : 24 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, recursive types and interfaces are constructs that reference themselves within their definitions, enabling the modeling of complex, nested data structures.

  • They are particularly useful for representing hierarchical data such as trees and linked lists.
  • By allowing types to be defined in terms of themselves, TypeScript facilitates the creation of flexible and dynamic data models.

Recursive Interfaces

Recursive interfaces in TypeScript allow an interface to reference itself within its definition, enabling the modeling of hierarchical data structures like trees or linked lists.

Syntax:

interface RecursiveInterface {
value: any;
next?: RecursiveInterface;
}
JavaScript
interface ListNode {   value: number;   next?: ListNode; }  const node1: ListNode = { value: 1 }; const node2: ListNode = { value: 2, next: node1 };  console.log(node2); 
  • ListNode interface defines a node containing a value and an optional next property referencing another ListNode.
  • node1 is a single node with a value of 1.
  • node2 is a node with a value of 2, pointing to node1 as its next node.

Output

{
value: 2,
next: {
value: 1
}
}

Recursive Type Aliases

Type aliases in TypeScript can also be recursive, allowing for flexible and complex type definitions, such as representing tree structures where each node can have multiple children.

Syntax:

type RecursiveType = {
value: any;
children?: RecursiveType[];
};
JavaScript
type TreeNode = {   value: string,   children?: TreeNode[], };  const tree: TreeNode = {   value: "root",   children: [     {       value: "child1",       children: [         {           value: "grandchild1",         },       ],     },     {       value: "child2",     },   ], };  console.log(tree); 
  • TreeNode type defines a node with a value and an optional children array containing other TreeNode elements.
  • tree represents a hierarchical structure with a root node having two children, one of which has its own child.

Output

{
value: "root",
children: [
{
value: "child1",
children: [
{
value: "grandchild1"
}
]
},
{
value: "child2"
}
]
}

Using Recursive Types with Generics

Combining recursive types with generics allows for the creation of self-referential structures that can handle various data types.

Syntax:

interface RecursiveGenericInterface<T> {
value: T;
next?: RecursiveGenericInterface<T>;
}
JavaScript
interface GenericListNode<T> {   value: T;   next?: GenericListNode<T>; }  const node1: GenericListNode<number> =      { value: 123 }; const node2: GenericListNode<number> =      { value: 456, next: node1 };  console.log(node2); 
  • GenericListNode interface uses a generic type T to define the type of value.
  • node1 and node2 are linked list nodes holding numeric values, demonstrating the flexibility of generics in recursive types.

Output

{
value: 456,
next: {
value: 123
}
}

Recursive Types for Function Definitions

Recursive types can also define functions that return themselves, useful for creating self-referential algorithms.

Syntax:

type RecursiveFunction = () => RecursiveFunction | null;
JavaScript
type RecursiveFunction = () => RecursiveFunction | null;  const recursiveFunction: RecursiveFunction = () => {   const stopCondition = true; // Replace with actual logic   return stopCondition ? null : recursiveFunction; };  console.log(recursiveFunction()); 
  • RecursiveFunction type describes a function that returns either itself or null.
  • recursiveFunction implements this type, returning null based on a condition, demonstrating a base case in recursion.

Output

null

Next Article
What are TypeScript Interfaces?
author
iamgaurav
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • What are intersection types in Typescript ?
    In Typescript, Although intersection and union types are similar, they are employed in completely different ways. An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of
    3 min read
  • What are string literal types in TypeScript ?
    The string literal type was added in TypeScript version 1.8. String literal types work well with union types and type aliases in practice. These properties can be combined to give strings enum-like functionality. The string literal type allows you to specify a set of possible string values for a var
    3 min read
  • What are template literal types in Typescript ?
    Template literal types in TypeScript allow the construction of new string literal types by combining existing string literal types using template literal syntax. They enable the creation of complex string patterns by embedding unions and other literal types within template literals.This feature enha
    3 min read
  • What are TypeScript Interfaces?
    TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity. Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
    4 min read
  • What is Recursive Generic in TypeScript ?
    In TypeScript, a recursive generic is a type that refers to itself within its definition, enabling the creation of data structures or types containing references to the same type within their structure. This capability proves invaluable when dealing with nested or hierarchical data structures like t
    4 min read
  • Recursive Type Guards In TypeScript
    In TypeScript type guards help determine the type of a variable at runtime, they are especially useful when dealing with complex types like unions, discriminated unions or even recursive structures and a recursive type guard is a type guard function that can handle complex nested types, including th
    6 min read
  • What is the Record Type in TypeScript ?
    In TypeScript, the Record type is a utility type that represents an object type with keys and values of a specific type. It is often used when you want to define a type for the keys and values of an object. In this article, we will learn what is the Record type in TypeScript. Syntax:Record<Keys,
    2 min read
  • What is Type Erasure in TypeScript?
    TypeScript is a very mighty superset of JavaScript, which adds static typing to the language and allows developers to catch errors early on as well as write more maintainable code. This being said a TypeScript type system erases type information at compile time (or during the compilation), a phenome
    4 min read
  • What is Type Predicates in Typescript ?
    In this article, we are going to learn about the type predicates in Typescript. TypeScript is a statically typed programming language that provides many features to make your code more efficient and robust. Type predicates in TypeScript are functions that return a boolean value and are used to narro
    3 min read
  • What is the difference between interface and type in TypeScript ?
    In TypeScript, both interface and type are used to define the structure of objects, but they differ in flexibility and usage. While interface is extendable and primarily for object shapes, type is more versatile, allowing unions, intersections, and more complex type definitions. Type in TypeScriptTh
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences