Recursive types and interfaces in TypeScript

When writing out a type or interface in TypeScript for something that will
be fed into a recursive function
you could cop out and use any or you could properly define the structure.

Fortunately, both type and interface allow you to be self referential in
terms of defining properties.

Let’s say you have an array of objects that looks like this:

const recursiveData = [
  {
    name: 'First',
    children: [
      {
        name: 'Second',
        children: [
          {
            name: 'Third',
            children: [
              {
                name: 'Fourth',
                children: [
                  {
                    name: 'Fifth',
                    children: [
                      // On and on...
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  },

We could very well just define a type or interface with the exact number of
levels that we see here, but it wouldn’t handle the open ended nature of the
// On and on... comment.

For scenarios where the data structure isn’t predictable, we can define a type
like this:

type RecursiveObject = {
  name: string
  children?: RecursiveObject


type RecursiveObjects = RecursiveObject

If you’d rather use an interface instead, just adjust the syntax:

interface RecursiveObject {
  name: string
  children?: RecursiveObject
}

// and reference it as
const recursiveData: RecursiveObject

Since your type or interface can reference itself as such, you’re all set!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.