最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return react 16 array elements in typescript - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Oct 13, 2017 at 21:18 Erik Philips 54.6k11 gold badges131 silver badges156 bronze badges asked Oct 9, 2017 at 9:49 David SpiessDavid Spiess 6871 gold badge11 silver badges24 bronze badges 2
  • 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 Commented Oct 9, 2017 at 11:53
  • Thanks for the link! – David Spiess Commented Oct 9, 2017 at 15:07
Add a comment  | 

2 Answers 2

Reset to default 7

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

Or use React fragments:

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

评论列表(0)

  1. 暂无评论