BenjiFB BenjiFB - 3 years ago 433
React JSX Question

React+Redux+Typescript: Error when trying to instantiate connect-wrapped component: Type {} is not assignable to

I'm starting with the React+Redux template that ships with vs2017. All I'm doing is trying to instantiate a "connected" component wrapper. My understanding is that if connect worked, the resulting type should not expect anything to come in via props when the wrapped component is instantiated (since the mapping to props happens internally). Yet based on the below error, it seems like it's complaining that I'm not passing in "count" via props, yet count is supposed to come from the redux store as I mapped it in.

Error TS2322 (TS) Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & R...'.
Type '{}' is not assignable to type 'Readonly'.
Property 'count' is missing in type '{}'. WebApplication1 (tsconfig project) C:\Users\ben\Documents\Visual Studio 2017\Projects\WebApplication1\WebApplication1\ClientApp\components\FetchData.tsx 29 Active

state defined:

export interface CounterState {
count: number;
}


connect called:

export default connect(
(state: ApplicationState) => state.counter, CounterStore.actionCreators)(Counter) as typeof Counter;


I think it's suspect that the template appears to be typecasting the wrapped connected component to the shape of the original component, but I'm not sure about this.

Instantiate here:

import Counter from '../components/Counter'
....
public render() {
return <div>
<Counter />
<h1>Weather forecast</h1>


Am I incorrect in thinking that I can instantiate a connect-wrapped container component without passing in the required props since they should come from the redux store?

Update: I've uploaded the reproducible testcase here: https://drive.google.com/file/d/0B_eEp0KGxixWN0tQTE1ac2FQYnc/view?usp=sharing

Just open the solution with VS2017 15.3.5, and after it restores the node_modules, you can either run the solution to view the error, or you can open the file ClientApp/Components/FetchData.tsx , and the error will be displayed in the error list.

Answer Source

That as typeof Counter is indeed the problem. By typing your connected component as a Counter, you specify that it still needs the count prop, which it doesn't. If you drop the typeof, there's an error in routes.tsx, which you can fix by installing the most recent types/react-router (4.0.15), which doesn't require the component in a Route to have RouteComponentProps anymore. You'll probably also want to use the most recent @types/react-redux, to get more accurate types for connected components.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download