Reputation: 3798
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.
Upvotes: 4
Views: 1370
Reputation: 2115
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>
Upvotes: 2