An argument of type "Element" is not assigned to a parameter of type "ReactElement <any>
This code:
import * as React from 'react'; const Component = () => <div/>; function culprit<P>(node: React.ReactElement<P>) { console.log(node); } culprit(<Component/>);
... creates this compilation error when compiling with TypeScript:
error TS2345: Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any>'. Type 'null' is not assignable to type 'ReactElement<any>
This happens when the strictNullChecks TypeScript compilation flag is set to true
.
Yes, I can turn off this flag, but I want it to be turned on for additional verification / compile-time security.
If I change the last line to this:
culprit( (<Component/> as React.ReactElement<any>) );
... it works with a flag set to true
.
I recently tried switching from “regular” JavaScript to TypeScript in a React project, and this disables all my tests, so adding all TypeScript statements to all of these occurrences in the test code will be a pain.
Is this a mistake or I have no other choice?
This is apparently the problem that was introduced in the React 15.0.5 type definitions. If you go to 15.0.4, everything should be fine.
See this problem: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/14284
For me, the problem was something else that I identified after a hard time.
If your JSX inside your component or component test file must have a .tsx extension. My test or code compiled as I saved them as a .ts file.
Also note that I used Typescript, so I renamed it to .tsx, if you use ES6, rename it to .jsx