Home > Enterprise >  How to combine object-or-array and recursion in Typescript?
How to combine object-or-array and recursion in Typescript?

Time:12-27

Essentially I want to achieve this:

type Foo = ({bar: string} & Record<string, Foo>) | Foo[]

I keep running into either circular reference drawback for type or
An interface can only extend an object type or intersection of object types with statically known members for interface, with something like this:

type Atom = { bar: string } & Record<string, Foo>
type ArrayOrRecord = Atom | Array<Atom>
interface Foo extends ArrayOrRecord {}

There was a similar question raised here Recursive array type typescript, but the difference is that in my case Atom has recursive properties as well.

CodePudding user response:

Just expand the Record definition:

type Foo = ({bar: string} & { [K in string] : Foo }) | Foo[]
  • Related