简体   繁体   中英

Typescript: type inference for children on generic react component

Given a react component that is generic on two properties, a load function returning type T , and the children (which is a single function taking a parameter of type T )...

class Test<T> extends React.Component<{
  load: () => T;
  children: (r: T) => JSX.Element;
}> {
  render() {
    return this.props.children(this.props.load());
  }
}

typescript is not able to infer the type of res from the return value of load , it defaults to type {} .

<Test load={() => ({ test: 'x' })}>
  {res =>
    <span>
      {res.test}
    </span>}
</Test>;

Is this a bug, or is typescript not able to infer based on return values -- as it looks like typing of JSX children is supported.

EDIT:

for background, the usecase is creating a "lazy" component which accepts load function which return a promise resolving to some further JSX.

Update: In the meantime TypeScript has been improved, such that the code given in the question automatically infers the type for res . I haven't checked which change was responsible for that, but I guess it happened somewhere around 3.0-3.3.


I think the problem is that your code gets transpiled to something similar to:

React.createElement(
  Test,
  {load: () => ({ test: 'x' })},
  res =>
    <span>
      {res.test}
    </span>
)

From that situation it is more clear that it would be very hard for the compiler/definitions to correctly infer the generic parameter. In your situation it would be enough to tip the compiler:

<Test load={() => ({ test: 'x' })}>
    {(res: { test: string }) =>
        <span>
            {res.test}
        </span>}
</Test>

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