21

In what to me seems like two similar setups, on one machine I was allowed to call

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

Where MyApp had the class signature

export interface IMyAppProps {
  accountId: string;
  dispatch: any;
}
    class MyApp extends React.Component<IMyAppProps, IMyAppState> {

On the other machine, running npm run-script build fails with

TypeScript build error TS2322: Type ' ... ' is not assignable to type ' ... '

Property 'children' does not exist on type 'IntrinsicAttributes & Pick<IMyAppProps, "accountId">'

Versions used on both machines react-scripts-ts 4.0.8, typescript 3.4.5.

Changing the class definition to this made it work on both machines

class MyApp extends React.Component<React.PropsWithChildren<IMyAppProps>, IMyAppState> {

I am unsure why it works in one setup and not the other. When do I wrap my props interface in React.PropsWithChildren?

My best guess would be that the change is to be found in a typings file for React or for a React-related package.

reymon359
  • 1,240
  • 2
  • 11
  • 34
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48

2 Answers2

10

I don't know why it worked on one machine but not the other but I don't think that's the right way to use the children property.

Instead of this ...

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

... I think the purpose of children is to let you call something like this ...

<MyApp accountId={this.props.accountId}>
  <ToggleButton/>
</MyApp>

... or something like that.

The child or children -- <ToggleButton/> in my example above -- might be a React element, or text (a text node), or undefined if there is no child, or maybe an expression like {toggleButton} which evaluates to one of the child types.

ChrisW
  • 54,973
  • 13
  • 116
  • 224
2

The actual answer has nothing to do with whether you use <MyApp children={...} or <MyApp><Child /></MyApp>. The difference is that in the first example IMyAppProps does not have a children property defined, so TypeScript complains that you can't use it like that. When you wrap it in WithChildren that adds a children property to the interface.

Jason Kohles
  • 597
  • 5
  • 12
  • We didn't have this issue until now, we haven't even updated React, then suddenly, boom this explodes in our face for the entire codebase. Where does it come from? – Kev May 29 '22 at 12:38
  • 1
    My guess would be that you probably didn't have this error before because you didn't have `@types/react` installed so there was nothing for it to check, and thens somebody added it. – Jason Kohles Jun 02 '22 at 20:00