My array is of type object[] & Tree[]
, but when using arr.map(child => ...)
, the type of child is inferred as object
instead of object & Tree
.
Is there a way to avoid this without additional casting?
It's worth noting that Tree
extends object
, but TypeScript doesn't recognize this and merge the two parts of the intersection type.
EDIT - Here's a minimal reproducible example:
While this example is contrived, it is based on another recent question I had: 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: []
}]
});
In this code snippet, "basicTree" has an inferred type. While I have defined BasicInterface in this example, in reality, it is generated automatically and I haven't found a way to programmatically generate a recursive interface.
I want to add back the recursive type of children as defined in the original interface.
Instead of completely redefining BasicInterface in the code (which could be cumbersome), I am attempting to "enhance" the type definition of basicTree with the correct recursive definition.
However, this approach falters when trying to determine the type of children. Is there a simpler solution available?
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);