【问题标题】:Type for nested objects with specific leaf types具有特定叶类型的嵌套对象的类型
【发布时间】:2017-05-05 16:20:46
【问题描述】:

我想要一个嵌套对象的类型,在它们的叶子上有一个特定的类型。

我希望这是正确的:

let a: Leaves<number> = {
    "foo": 1,
    "bar": {
        "baz": 2
    }
};

这会失败:

let a: Leaves<number> = {
    "foo": 1,
    "bar": {
        "baz": 'something else' // Leaf of type string
    } 
};

我试过了

export type Leaves<T> = {
    [P in keyof T]: T | Leaves<T>;
}

但是,对于该定义,两个示例都给出了编译错误。第一个说Type '{ "foo": number; "bar": number; }' is not assignable to type 'number'.

有没有办法解决这个问题?

【问题讨论】:

    标签: typescript recursive-datastructures


    【解决方案1】:

    如果您需要具有任意键的节点的类型,以及作为叶子或其他节点的值,indexable type 是要走的路:

    export type Leaves<T> = {
        [n: string]: T | Leaves<T>
    }
    

    (顺便说一句,我宁愿称它为Node&lt;T&gt;,而不是Leaves&lt;T&gt;

    映射类型在这里不适合,因为这样的映射类型

    {
        [P in keyof T]: T | Leaves<T>;
    }
    

    只能拥有T 拥有的属性——这就是[P in keyof T]: 所说的。当Tnumber 时,这意味着映射类型只能具有number 类型中的属性,并且因为number 是原始的,它本质上意味着它与number 相同。这就是 not assignable to number 错误消息的原因 - 打字稿试图找到最具描述性的类型以显示在错误消息中,而在您的情况下,它只是 number

    【讨论】:

    • 谢谢,这很有帮助。我想我有点困惑。
    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多