Hector Crean
Hector Crean

Reputation: 332

Typescript recursive types

Just trying to get my head around creating typings for recursive data structures. Can anyone give any refinements on what should be done? i.e. currently linting complains if I set:

const graph: INestedGraph<typeof data> = data; 

Any help would be massively appreciated!

interface INestedGraph<T> {
    name: string;
    position?: number[];
    children?: T[] extends INestedGraph<infer U>[] ? INestedGraph<U>[]: null[]; 
}
const data =  {
    name: "root",
    children: [
      {name: "child #1"},
      {name: "child #2",
        children: [
          {name: "grandchild #1",
            children: [{name: "great-grandChild#1"}]},
          {name: "grandchild #2"},
          {name: "grandchild #3"}
        ]
      }, 
      {name: 'child #3', 
        children: [
            {name: 'grandchild #6'}
        ]}
    ]
  }; 

Upvotes: 0

Views: 116

Answers (1)

Rubydesic
Rubydesic

Reputation: 3476

Can't you just do this?

interface INestedGraph {
    name: string;
    position?: number[];
    children?: INestedGraph[]
}

Upvotes: 3

Related Questions