2

Is it possible in Typescript to define a type with an arbitrary number of nested objects?

To simplify the question, let's only consider typing a basic JSON object that only has string entries. So, a property of this JSON object would either be another basic JSON object, or a string.

This would be an example:

const obj = {
    propA: 'a string';
    propB: {
        propA: 'a string';
        propB: {
            propA: 'a string';
        }
    };
}

So this example has a "depth" of 2 (or 3, depending on how you count).

Is it possible to type this object, but more generally any object with arbitrary depth? I couldn't come up with a solution, particularly recursive types are disallowed in Typescript, i.e.

type A = A & string | string; // does not compile

I could not define a type using helper types either, for the same reason. At some point, a type had to be self-referential, at least in my experience.

Anthony
  • 1,015
  • 8
  • 22
  • https://stackoverflow.com/questions/36966444/how-to-create-a-circularly-referenced-type-in-typescript ? – Andy Ray Apr 21 '19 at 05:31
  • Wow, from the creator himself! I believe this answers my question. If it does, I'll report back. – Anthony Apr 21 '19 at 05:41
  • Possible duplicate of [How to create a circularly referenced type in TypeScript?](https://stackoverflow.com/questions/36966444/how-to-create-a-circularly-referenced-type-in-typescript) – Andy Ray Apr 21 '19 at 05:42
  • Works :) thanks for the link! – Anthony Apr 21 '19 at 06:31

0 Answers0