首页 > 解决方案 > 获取通用对象字段作为数组

问题描述

我有一个对象,我想serviceElementsGenericComponent.

对象

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以在其上循环呢?

我已经添加了代码框

标签: javascripttypescripttypescript-generics

解决方案


你可能需要.map()

data.map(m => m.serviceElements)
    .forEach(se => {
        // TODO: THINGS
    });

推荐阅读