递归泛型类型 - 深度类型检查

6
我想创建一个递归的泛型类型TRecursive,基于我的数据接口IOne、ITwo和IThree,它们的关系如下所示。 TRecursive 的结果类型应该与 IOne 有类似的关系,但不同的值类型,例如下面的示例中的布尔类型。
interface IOne {
    pk: number;
    name: string;
    two: ITwo;
}

interface ITwo {
    pk: number;
    name: string;
    three: IThree;
}

interface IThree {
    pk: number;
    name: string;
}

type TRecursive<T> = {
    [P in keyof T]?: TRecursive<T[P]> | boolean;
};

const test: TRecursive<IOne> = {
    pk: true,
    name: true,
    two: {
        pk: true,
        name: true,
        anything: true,        // type error as expected
        three: {
            pk: true,
            name: true,
            anything: true     // no error - why?
        }
    }
};

事情是这样的,当我需要在相关类型中进行类型检查时,我无法使typescript@2.3.3正常工作。
我添加了一个未在我的数据类型中定义的关键字anything,因此我希望typescript在这里显示错误。如预期所见,在一级深度(在关键字two内部)中我看到了错误,但是同样的关键字在两级深度(在关键字three内部)中不会触发错误。
为什么会这样?有什么办法可以用typescript实现这个目标吗?

我能想到的唯一解释是这是编译器的错误。也许在TS GitHub存储库中开一个问题? - Benjamin Hodgson
1个回答

0

这在TS中非常常见。它会在继续查找下一个错误之前停止在第一个错误处。

const test: TRecursive<IOne> = {
    pk  : true,
    name: true,
    two : {
        pk   : true,
        name : true,
        // anything: true,
        three: {
            pk      : true,
            name    : true,
            anything: true, // error
        },
    },
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接