Would someone know why addChildrenDefaultValue works but addChildrenDefaultValue2 throws
Type '(Omit<T, "children"> & { children: ObjectWithChildren<TestObject>[]; })[]' is not assignable to type 'ObjectWithChildren<T>[]'.
Type 'Omit<T, "children"> & { children: ObjectWithChildren<TestObject>[]; }' is not assignable to type 'ObjectWithChildren<T>'.
Type 'Omit<T, "children"> & { children: ObjectWithChildren<TestObject>[]; }' is not assignable to type 'T'.
'Omit<T, "children"> & { children: ObjectWithChildren<TestObject>[]; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'TestObject'.(2322)
? Is there a better way to do this? (I'm using extends cause in my use case it extends more types)
interface TestObject{
name: string;
children?: TestObject[] | null;
}
type ObjectWithChildren<T> = T & {children: ObjectWithChildren<T>[]};
function addChildrenDefaultValue(
taxonomy: TestObject[]
): ObjectWithChildren<TestObject>[] {
return taxonomy.map(({children, ...props}) => {
return {...props, children: addChildrenDefaultValue(children ?? [])};
});
}
function addChildrenDefaultValue2<T extends TestObject>(
taxonomy: T[]
): ObjectWithChildren<T>[] {
return taxonomy.map(({children, ...props}) => {
return {...props, children: addChildrenDefaultValue2(children ?? [])};
});
}