javascript - 获取通用对象字段作为数组
问题描述
我有一个对象,我想serviceElements
在GenericComponent
.
对象
interface MyObject {
id: number;
serviceElements: ServiceElement[];
}
interface ServiceElement {
id: number;
}
通用组件
interface Props<Type> {
service: GenericService<Type>;
}
export default class GenericComponent<Type> extends React.Component<Props, {}> {
....
private fillDataTable = (): void => {
service.list().then((data: Type[]) => {
data.forEach(record => {
// 1st attempt
const array: ServiceElement[] = record['serviceElements'];
// record['serviceElements'] gives the error:
/* TS7053: Element implicitly has an 'any' type because expression of type '"serviceElements"' can't be used to index type 'unknown'.
Property 'serviceElements' does not exist on type 'unknown'.
*/
//////////////
// 2th attempt
const array: ServiceElement[] = record['serviceElements' as keyof Type];
// const array gives the error:
/* TS2322: Type 'Type[keyof Type]' is not assignable to type 'ServiceElement[]'.
Type 'Type[string] | Type[number] | Type[symbol]' is not assignable to type 'ServiceElement[]'.
Type 'Type[string]' is not assignable to type 'ServiceElement[]'.
*/
}
}
}
....
}
在页面内部,GenericComponent
将像这样使用:
<GenericComponent<MyObject> service={new MyObjectService()}/>
那么,我怎样才能以数组的形式GenericComponent
进入record
's 字段serviceElements
以在其上循环呢?
我已经添加了代码框
解决方案
你可能需要.map()
data.map(m => m.serviceElements)
.forEach(se => {
// TODO: THINGS
});
推荐阅读
- javascript - 为什么 xaxis 和 yaxis 刻度不出现在 D3 的轴上?
- django - Get Data from Multiple ForeignKey Query Results
- python - 通用数学方程
- c++ - 使用文件中的数字作为输入来计算它们 c++
- python - python将列表与列表的比较列表
- javascript - ReferenceError:当我使用 vuejs 设置 PayPal Checkout 时,未定义 paypal
- java - java.lang.IllegalArgumentException:插件已经初始化
- terraform - Terraform:无法配置 aws ecs 自动缩放集群
- latex - 乳胶缺失 $ 插入
- nativescript - Nativescript update UI on ObservableArray push