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
CodePudding user response:
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)),
};
}