[英]Typescript dynamic object interface
I'm using javascript to create an object and want to add in an interface for the data:我正在使用 javascript 创建一个 object 并希望添加一个数据接口:
Javascript: 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}
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:感谢 Nikita Madeev,我设法让它与这个一起工作:
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);
Children.children
- object, not array, object has not push method Children.children
- object,不是数组,object 没有推送方法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
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.