0

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'}
        ]}
    ]
  }; 

1 Answer 1

3

Can't you just do this?

interface INestedGraph {
    name: string;
    position?: number[];
    children?: INestedGraph[]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Definitely a good option. But I think there is some mechanism to limit the depth to which the data structure is searched to conform to the type. One of Typescript 4.0's new features seems to be 'recursive types' and was wondering if anyone had any knowledge on them.
@HectorCrean what is your goal? You should put it in the question. You need a tree type that can only have a max depth?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.