简体   繁体   中英

How do you import untyped ES6 react components into a Typescript component without typing the JS child components?

If I have an ES6 component like so:

 component OldThing extends React.Component { constructor(props) { super(props); } render() { return <div>{this.props.someProp}</div>; } } 

an ES6 container like so:

 const OldThingContainer = connect(mapStateToProps, mapDispatchToProps)(OldThing); 

and a new typescript component like so:

 component NewThing extends React.Component<Props, State> { render() { return <OldThingContainer someProp={someValue} /> } } 

I currently get an IntrinsicAttributes error about someProp not existing on OldThing. How do I get rid of that error without adding types/typedefs to/for OldThing and/or OldThingContainer? I tried the @augments solution on the OldThingContainer where it's defined but that doesn't seem to help. Neither did adding the comment on the component itself.

The reason I want to be able to import JS without types is that we are adding typescript to a very large, multiple years old code base and it's currently difficult to get people to write typescript components at all, let alone if they also have to type out every existing component their component wants to import.

Is there an existing elegant solution to this problem or am I going to have to go through ahead of everyone and manually type every existing JS component (hundreds) in some typedef file to get rid of/prevent these errors?

I tried your example and it seemed some issue with the type connect inferred for your component.

One quick'n'dirty fix would be to annotate your JS component with:

/**
 * @type {React.ComponentType<any>}
 */
const OldThingContainer = connect(mapStateToProps, mapDispatchToProps)(
  OldThing
);

One more elegant fix (but maybe not possible) would be trying to dive into the react-redux typings. The connect function requires you to supply some type arguments for it to properly work. When not supplied, those arguments are given {} , not any (because any can silently eat your types).

Comment: From the few I've worked with react+redux+typescript, lib typedefs are one of the biggest pain points. React typedefs can get really complicated. (flow just will hang up your editor with "waiting for flow server", which is even worse). As TS+Redux gets more popular and more support is added, this may get a lot better in a few months...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM