Return react 16 array elements in typescript

♀尐吖头ヾ 提交于 2019-11-29 18:37:31

问题


I want to use the new react 16 feature to return array elements in my render but i'm getting the typescript error Property 'type' is missing in type 'Element[]'

const Elements: StatelessComponent<{}> = () => ([
  <div key="a"></div>,
  <div key="b"></div>
]);

What am i missing? Using @types/react 16.0.10 and typescript 2.5.3


回答1:


I checked the latest typings and they forgot to add new definitions in a stateless component interface. I've raised the issue and it should be fixed soon.

Returning an array from class components works so if you really need it right now you can transform your functional component to class component.

class Elements extends React.Component<{}> {

  render() {
    return [
       <div key="a"></div>,
       <div key="b"></div>
    ]

  }
}

or temporarily extend React typings using module augmentation. Just put the following code somewhere in one of your .ts files and typescript will automatically detect changes in definitions.

declare module "react" {
  interface StatelessComponent<P = {}> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any>[] | ReactElement<any> | null;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
  }
}



回答2:


Or use React fragments:

render() {
    return 
       <>
        <div key="a"></div>,
        <div key="b"></div>
       </>
}


来源:https://stackoverflow.com/questions/46643517/return-react-16-array-elements-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!