I have an array of type object[] & Tree[]
but arr.map(child => ...)
infers the type of the child as object
rather than object & Tree
.
Is there any way to avoid this without extra casting?
Notably Tree
extends object
but typescript doesn't seem to realise this and merge the two parts of the intersection type.
EDIT - Minimal reproducible example:
This is contrived, but based off my other recent question Transform a typescript object type to a mapped type that references itself
interface BasicInterface {
name: string;
children: object[];
}
function getBasic<T extends object>(input: T): BasicInterface {
return input as BasicInterface;
}
export const basicTree = getBasic({
name: 'parent',
children: [{
name: 'child',
children: []
}]
});
The point is the code below has access to "basicTree" and its inferred type. For this example I have defined BasicInterface, but in practice this is generated automatically and I haven't found a way to programatically generate a recursive interface.
I would like to add the recursive type of children back as the original interface defines.
Rather than completely redefine BasicInterface in the code as this could be a lot of boilerplate, I am trying to "enhance" the definition of the basicTree's type with the correct recursive definition.
But this falls down when getting the children's type. Perhaps there is a simpler solution?
type RestoredInterface = typeof basicTree & {
children: RestoredInterface[]
};
function getTree(basic: BasicInterface): RestoredInterface {
return basic as RestoredInterface;
}
const restoredTree = getTree(basicTree);
const names = restoredTree.children.map(child => child.name);