打字稿array.map无法正确分配相交类型

时间:2020-02-19 17:06:10

标签: typescript intersection array-map mapped-types

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

有没有其他方法可以避免这种情况?

值得注意的是,Tree扩展了object,但打字稿似乎并没有意识到这一点,并且无法合并交叉点类型的两个部分。

编辑-最小的可重现示例:

这是人为的,但基于我最近的另一个问题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,但实际上这是自动生成的,我还没有找到以编程方式进行编程的方法 生成一个递归接口。

我想在原始接口定义的基础上添加子代的递归类型。

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

但是在获得孩子的类型时,这种情况会下降。也许有一个更简单的解决方案?

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

2 个答案:

答案 0 :(得分:1)

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

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

编辑:这是explanation

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

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

请参见Playground

答案 1 :(得分:0)

基于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
});
相关问题