1

I want to have an object like this:

{
  a1: {
    b1: {
      c1: {
        d1: 'foo',
        d2: {
          e1: 'bar'
        },
        d3: 'baz'
      },
      c2: 'hello'
    },
    b2: 'world',
    b3: {
      c1: {
        d1: 'another',
        d2: 'nested',
      }
    }
  },
  a2: 'thing'
}

Basically, the value associated with any key can be either a string or Record<string, recurse>... How can I accomplish this in TypeScript?

My attempt was:

type NestedRecordStringType = Record<string, RecordOrStringType>

type RecordOrStringType = string | Record<string, RecordOrStringType>

But it results in:

Type alias 'RecordOrStringType' circularly references itself.ts(2456)

How do I accomplish this sort of thing? I would then create a map:

const map: MyType = {
  a1: {
    b1: {
      c1: {
        d1: 'foo',
        ...
      }
    }
  }
}

It must be something obvious I am missing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lance
  • 75,200
  • 93
  • 289
  • 503
  • 3
    Does this answer your question? [Recursive Types in TypeScript](https://stackoverflow.com/questions/47842266/recursive-types-in-typescript) – possum Apr 11 '23 at 11:33

1 Answers1

2

Write it without using Record

type MyType = string | {
    [key: string]: MyType
}

Playground

Teneff
  • 30,564
  • 13
  • 72
  • 103