This is a follow-up of Interface Depending on the Types of a Recursive Property
Sorry if it looks like "write my code" questions, it's surely not meant to be something like that! I'm just getting started with advanced typings and I find it hard to grasp the possibilities I have to express types. So please bear with me :)
In my code I want to convert an object into a tree structure. The code is already doing that, but I want the types to reflect that properly. The code traverses each property of an object (or items if array) and turn them into nodes.
See Stackblitz for detailed example
My current approach:
interface Node<Type, Children> {
value: Type,
children: Children[],
}
function treeOf<T>(
value: T,
): Node<
T,
{
[K in T]: Node<T[K], any[]>[]
},
>
... gives me a TypeScript error:
Type 'Node<{ [x: string]: T[any]; }, any[]>' does not satisfy the constraint 'Node<unknown, any[]>[]'.
Type 'Node<{ [x: string]: T[any]; }, any[]>' is missing the following properties from type 'Node<unknown, any[]>[]': length, pop, push, concat, and 26 more.
... and it also cannot handle arrays properly I think, as it considers an array's properties ("push", "pop", ...) instead of its items.
I also tried
function treeOf<T>(
value: T,
): Node<
T,
Node<
{
[K in T]: T[K];
},
any[]
>
> {
... but to no avail.
Again I don't know if this is possible with TypeScript as well, or if I am requesting to much now. But maybe someone can tell me :)