12
votes

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

2
it's still a fresh version and the typings are not quite ready. Here you have a link where you can follow progress: github.com/DefinitelyTyped/DefinitelyTyped/pull/19363 (they merged it a few days ago but people are still having issues)niba
Thanks for the link!David Spiess

2 Answers

8
votes

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;
  }
}
6
votes

Or use React fragments:

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