Recursive types and interfaces in TypeScript

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles