简体   繁体   中英

Typescript dynamic object interface

I'm using javascript to create an object and want to add in an interface for the data:

Javascript:

const childGroups: Children = {};
      childGroups.children = [];

// Pushing some data 
childGroups.children.push(children);

Interface:

export interface Child {
    ClusterPoint
}

export interface Children {
    children: {
        [key: number]: Child
    }
}

I'm getting the below errors: Property 'children' is missing in type '{}' but required in type 'Children'. Property 'push' does not exist on type {[key: number]: Child} Property 'children' is missing in type '{}' but required in type 'Children'. Property 'push' does not exist on type {[key: number]: Child}

The data looks this:

在此处输入图像描述

Any help would be appreciated.

Update

Thanks to Nikita Madeev, I managed to get it to work with this:

export interface Child {
    children: {
        ClusterPoint
    };
}

export interface Children {
    children: Child[];
}
export interface Child {
    ClusterPoint;
}

export interface Children {
    children: Child[];
}

const childGroups: Children = { children: [] };

// Pushing some data
childGroups.children.push(newChildren);
  1. Children.children - object, not array, object has not push method
  2. During initialization, you need to specify all the necessary properties

If you want to achieve this structure

const childGroups: Children = {};
      childGroups.children = [];

then interfaces would be

export interface Children {
    children?: Child[];
}

and if you want to achieve this structure

const childGroups: Children = {};
      childGroups.children = {[some_id]: some_childValue};

then interface would be

export interface Children {
    children?: {
      [key: number]: Child
     };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM