Typescript, generic, функция. Типизация возвращаемого значения
Есть функция createTrees, отлично работающая на простом JS, пытаюсь её типизировать, но не могу понять как типизировать возвращаемое значение.
const data = [
{
_id: "6258460841beb0b276d1312e",
name: 'root1',
status: 'root',
description: 'root1-desc',
},
{
_id: "6258463e41beb0b276d13135",
parentId: "6258460841beb0b276d1312e",
name: 'branch1.1',
status: 'branch',
description: 'branch1.1-desc',
},
{
_id: "6259c7af6ab55bfcc4060524",
name: 'root2',
status: 'root',
description: 'root2-desc',
},
{
_id: "6259c7bc6ab55bfcc4060528",
parentId: "6258463e41beb0b276d13135",
properties: [],
name: 'leaf1.1',
status: 'leaf',
description: 'leaf-desc',
},
{
_id: "625aed38e43c85ac38c05636",
parentId: "6259c7af6ab55bfcc4060524",
name: 'branch2.1',
status: 'branch',
description: 'branch2.1-desc',
}
]
interface ITreeDataEl {
_id: string
name: string
parentId?: string
}
interface ITree { // ????
_id: string
name: string
children: Array<ITree>
}
function createTrees<T extends ITreeDataEl>(data: T[] , parentId?: string) {
let d: T[] = [];
const trees: ITree[] = []; // ????
if(!parentId) {
d = data.filter((item) => {
return item.parentId === undefined;
});
}
else {
d = data.filter((item) => {
return item.parentId?.toString() === parentId.toString();
});
}
for(let i=0; i<d.length; i+=1) {
const tree = {...d[i], children: createTrees(data, d[i]._id)};
delete tree.parentId;
trees.push(tree);
}
return trees;
}
const trees = createTrees(data);
Результат:
[
{
_id: "6258460841beb0b276d1312e",
name: 'root1',
status: 'root',
description: 'root1-desc',
children: [
{
_id: "6258463e41beb0b276d13135",
parentId: "6258460841beb0b276d1312e",
name: 'branch1.1',
status: 'branch',
description: 'branch1.1-desc',
children: [
{
_id: "6259c7bc6ab55bfcc4060528",
parentId: "6258463e41beb0b276d13135",
properties: [],
name: 'leaf1.1',
status: 'leaf',
description: 'leaf-desc',
},
]
},
]
},
{
_id: "6259c7af6ab55bfcc4060524",
name: 'root2',
status: 'root',
description: 'root2-desc',
children: [
{
_id: "625aed38e43c85ac38c05636",
parentId: "6259c7af6ab55bfcc4060524",
name: 'branch2.1',
status: 'branch',
description: 'branch2.1-desc',
children: [],
},
]
},
]