Typescript array.map 没有正确分配交集类型

标签 typescript intersection array-map mapped-types

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

有没有办法避免这种情况而无需额外的转换?

值得注意的是 Tree extends object 但 typescript 似乎没有意识到这一点并合并了交集类型的两个部分。

编辑 - 最小可重现示例:

这是人为的,但基于我最近的另一个问题 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: []
    }]
});

重点是下面的代码可以访问“basicTree”及其推断类型。对于这个例子,我定义了 BasicInterface,但实际上这是自动生成的,我还没有找到一种方法来编程 生成递归接口(interface)。

我想按照原始接口(interface)定义的方式添加递归子类型。

与其在代码中完全重新定义 BasicInterface,因为这可能是很多样板,我正在尝试 使用正确的递归定义“增强”basicTree 类型的定义。

但是当得到 child 的类型时,这会下降。也许有更简单的解决方案?

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);

最佳答案

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

type RestoredInterface = {
    children: RestoredInterface[]
} & typeof basicTree;

编辑:这是一个 explanation .

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

type RestoredInterface = Omit<typeof basicTree, 'children'> & {
    children: RestoredInterface[]
};

参见 Playground

关于Typescript array.map 没有正确分配交集类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60305687/

相关文章:

php - 从 array_map 匿名函数内部调用类方法

带有对象静态方法的php array_map

ajax - 在 Aurelias HTTP 客户端中捕获错误

java-创建一个简单的带旋转的 Sprite 多边形

java - 矩形的交集java

c# - 两个集合交集

php - 为什么 trim 不能作为 PHP 中 array_walk 或 array_map 的回调?

angular - ionViewWillEnter 与 ionViewDidEnter

javascript - 减少对象数组

object - 将对象转换为 TypeScript 中的接口(interface)