Typescript array.map不';t正确分配交叉口类型

Typescript array.map不';t正确分配交叉口类型,typescript,intersection,array-map,mapped-types,Typescript,Intersection,Array Map,Mapped Types,我有一个类型为object[]和Tree[]的数组,但是arr.map(child=>…)将子对象的类型推断为object而不是object和Tree 有没有什么方法可以避免这种情况而不需要额外施法 值得注意的是,树扩展了对象,但typescript似乎没有意识到这一点,并合并了交集类型的两个部分 编辑-最小可复制示例: 这是人为的,但基于我最近的另一个问题 我找到了一个奇怪的解决办法。只需更改声明中的顺序即可。这很奇怪,但它是有效的: type RestoredInterface = {

我有一个类型为
object[]和Tree[]
的数组,但是
arr.map(child=>…)
将子对象的类型推断为
object
而不是
object和Tree

有没有什么方法可以避免这种情况而不需要额外施法

值得注意的是,
扩展了
对象
,但typescript似乎没有意识到这一点,并合并了交集类型的两个部分

编辑-最小可复制示例:

这是人为的,但基于我最近的另一个问题


我找到了一个奇怪的解决办法。只需更改声明中的顺序即可。这很奇怪,但它是有效的:

type RestoredInterface = {
    children: RestoredInterface[]
} & typeof basicTree;
编辑:这里是一个例子

更好的解决方案可以是这样的:

type RestoredInterface = Omit<typeof basicTree, 'children'> & {
    children: RestoredInterface[]
};
type RestoredInterface=省略&{
儿童:修复接口[]
};

请参见

根据jcalz的观察,实际上可以简单地扩展原始接口。我很困惑,因为它是按程序定义的,但如果您先命名它,这不是问题:

type BasicTreeInterface = typeof basicTree;

interface RestoredInterface extends BasicTreeInterface {
    children: RestoredInterface[]
};

const restoredTree = getTree(basicTree);

const names = restoredTree.children.map(child => {
    // Child is of type RestoredInterface
});

函数的交叉点被解释为,因此调用
arr.map()
可能被认为是调用第一个重载;i、 例如,
object[]
map
方法。我想知道为什么类型不是
(对象和树)[
树[]
?十字路口在哪里?你能给我一个建议吗?啊,我明白了,谢谢。我将用一个示例来更新原始问题,以明确
basicTree
的推断类型只是
BasicInterface
,并且您的交集不会产生类似
object[]和Tree[]
;相反,它只是
object[]&其他非数组的东西
。您确定此示例再现了您的问题吗?
接口RestoredInterface extends BasicInterface{children:RestoredInterface[]}
可以执行您想要的操作吗?请注意,我认为上面的示例中有一个输入错误,因为您在一个我希望看到
RestoredInterface[]
的地方使用了
RestoredInterface
。在上面的示例中,您是否尝试过将
RestoredInterface
的定义更改为
接口RestoredInterface extends BasicInterface{children:RestoredInterface[]}
?这应该可以解决问题。如果这不能满足您的需要,请编辑示例代码以反映这一点。谢谢,这很有效。我还提出了一个解决方案,但当
typeof basicTree
更复杂时,这是唯一合适的解决方案。例如,如果它本身是联合类型,它没有静态已知的键,并且不能使用扩展
type RestoredInterface = Omit<typeof basicTree, 'children'> & {
    children: RestoredInterface[]
};
type BasicTreeInterface = typeof basicTree;

interface RestoredInterface extends BasicTreeInterface {
    children: RestoredInterface[]
};

const restoredTree = getTree(basicTree);

const names = restoredTree.children.map(child => {
    // Child is of type RestoredInterface
});