Definitelytyped: Incorrect type definition for React elements

Created on 17 Jan 2017  路  5Comments  路  Source: DefinitelyTyped/DefinitelyTyped

  • [ x] I tried using the latest xxxx/xxxx.d.ts file in this repo and had problems.
  • [ x] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
  • [x ] I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).
  • [x ] I want to talk about xxxx/xxxx.d.ts.

    • The authors of that type definition are cc/ @....

According to the official site, React components may return null to prevent any rendering. But due to a likely bug in the definition files, I get a type error when trying to use a component that possibly returns null. Here is the compiler error:

    (54,3): error TS2345: Argument of type '(props: PaginationProps) => Element | null' is not assignable to parameter of type 'ComponentClass<PaginationProps & {}> | StatelessComponent<PaginationProps & {}>'.
      Type '(props: PaginationProps) => Element | null' is not assignable to type 'StatelessComponent<PaginationProps & {}>'.
        Type 'Element | null' is not assignable to type 'ReactElement<any>'.
          Type 'null' is not assignable to type 'ReactElement<any>'.

I think the fix is to make ReactElement nullable

Most helpful comment

Should be ReactElement<any> | null. ReactNode allows string and boolean values, which is incorrect. @sbly, feel free to send a pull request.

All 5 comments

Currently we have this function definition for a StatelessComponent:

(props: P & { children?: ReactNode }, context?: any): ReactElement<any>;

I think the implication is that this should be:

(props: P & { children?: ReactNode }, context?: any): ReactNode

But I don't know for sure.

cc/ @pspeter3 @vsiao @johnnyreilly thoughts?

I haven't encountered this issue myself but I'm not using strictNullChecks - I wonder if this is a factor?

@johnnyreilly The problem only manifested when I turned --strictNullChecks on

Should be ReactElement<any> | null. ReactNode allows string and boolean values, which is incorrect. @sbly, feel free to send a pull request.

Another question: the typing for Component.render is JSX.Element | null, so shouldn't the return tyoe for a stateless component match that?

Was this page helpful?
0 / 5 - 0 ratings