获取通用对象字段作为数组

时间:2019-12-24 10:22:56

标签: javascript typescript typescript-generics

我有一个对象,我想在serviceElements内使用其数组属性GenericComponent

对象

interface MyObject {
    id: number;
    serviceElements: ServiceElement[];
}

interface ServiceElement {
    id: number;
}

GenericComponent

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的{​​{1}}字段record作为数组在其上循环?

我添加了codesandbox

1 个答案:

答案 0 :(得分:-1)

您可能需要.map()

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