0

I want to write generic recursive function like below

function withChildren<
  T extends {
    id?: string;
    parentId?: string;
  },
  TWithChild extends T & {
    children: TWithChild[];
  }
>(parentItem: T, items: T[]): TWithChild {
  const children = items.filter((ba) => ba.parentId === parentItem.id);

  return {
    ...parentItem,
    children: children.map((child) => withChildren(child, items)),
  };
}

but typescript throw an error

Type 'T & { children: (T extends BusinessAreaWithAccess ? BusinessAreaWithChildrenAndAccess : BusinessAreaWithChildren)[]; }' is not assignable to type 'T extends BusinessAreaWithAccess ? BusinessAreaWithChildrenAndAccess : BusinessAreaWithChildren'

i have search for the error, but still not found any solution

1
  • Please paste error-messages into the question, rather than screenshotting them. Commented Nov 25, 2022 at 8:53

1 Answer 1

1

TWithChild extends T & ..., meaning if used as explicit type parameter it can union e.g. {a: 1}, you don't know its exact type, so you can't instantiate it.
Define it as a known limited generic type, then it'll work

type TWithChild<T> = T & {children: TWithChild<T>[]}

function withChildren<
  T extends {
    id?: string;
    parentId?: string;
  }
>(parentItem: T, items: T[]): TWithChild<T> {
  const children = items.filter((ba) => ba.parentId === parentItem.id);

  return {
    ...parentItem,
    children: children.map((child) => withChildren(child, items)),
  };
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.