打字稿:如何为嵌套对象定义接口? [英] Typescript: How do I define interfaces for nested objects?

查看:27
本文介绍了打字稿:如何为嵌套对象定义接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个解析成这样的 JSON 负载:

Assume I have a JSON payload that parses into something like this:

{
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        }
    }
}

我将如何设置 Example 接口的定义以将 items 属性的值建模为一个对象,其键为字符串且其值由 Item 接口定义:

How would I set up the definition of the Example interface to model that the value of the items property is an object whose keys are strings and whose values are defined by the Item interface:

export interface Example {
    name: string;
    items: ???;

}

export interface Item {
    id: number;
    size: number;
}

推荐答案

Typescript 允许您使用语法 [key: string] 为对象键添加类型.

Typescript allows you to add a type for the object keys using the syntax [key: string].

如文档中所述,这些被称为 可索引类型:

As stated in the documentation, these are called indexable types:

可索引类型有一个索引签名,它描述了我们可以用来索引对象的类型,以及索引时相应的返回类型.

Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

在您的情况下,您将使用以下内容:

In your case, you would use the following:

export interface Item {
    id: number;
    size: number;
}

export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}

作为参考,这里有一个 链接到现场示例.

For reference, here is a link to a live example.

这篇关于打字稿:如何为嵌套对象定义接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆