【问题标题】:Nesting object declaration嵌套对象声明
【发布时间】:2021-08-29 09:53:15
【问题描述】:

有人可以帮我解决以下问题吗?

type Item = {
    id: number;
    size: number;
}
type Example = {
    name: string;
    items: [
        Item
    ];
}

var obj: Example = {
    name: "test",
    items: [
        {
            id: 1,
            size: 10
        },
        {
            id: 2,
            size: 34
        }
    ]
}

其实 items 应该是 Item 类型的列表,但我遇到了错误。

输入 '[{ id: number;尺寸:数量; }, { 身份证号码;尺寸:数量; }]' 不可分配给类型“[项目]”。源有 2 个元素,但 target 只允许 1.(2322)

【问题讨论】:

  • 试试吧:type Example = { name: string; items:Item []; }

标签: javascript reactjs typescript react-native


【解决方案1】:

你想要一个Item(s) 的数组,所以你需要写Item[]

type Example = {
    name: string;
    items: Item[]
}

您可以了解有关数组类型的更多信息here

数组:
要指定像[1, 2, 3] 这样的数组类型,可以使用语法number[];此语法适用于任何类型(例如,string[] 是一个字符串数组,等等)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2018-04-26
    • 2018-04-23
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多