Typescript: How do I define interfaces for nested objects?

后端 未结 1 1579
鱼传尺愫
鱼传尺愫 2020-12-07 11:53

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

{
    name: \"test\",
    items: {
        \"a\": {
            id: 1,
            size:          


        
1条回答
  •  星月不相逢
    2020-12-07 12:04

    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.

    0 讨论(0)
提交回复
热议问题