[英]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
)... 给定一个在两个属性上是通用的react组件,一个返回类型为
T
的load
函数和一个子类(它是一个带有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 {}
. typescript无法从
load
的返回值推断res
的类型,默认为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. 这是一个错误,还是打字稿无法根据返回值推断 - 因为它看起来像支持JSX子类型的输入。
EDIT: 编辑:
for background, the usecase is creating a "lazy" component which accepts load
function which return a promise resolving to some further JSX. 对于后台,usecase正在创建一个“懒惰”组件,它接受
load
函数,该函数返回一个解析为某些进一步JSX的promise。
Update: In the meantime TypeScript has been improved, such that the code given in the question automatically infers the type for res
. 更新:在此期间,TypeScript得到了改进,使得问题中给出的代码自动推断出
res
的类型。 I haven't checked which change was responsible for that, but I guess it happened somewhere around 3.0-3.3. 我没有检查哪个更改对此负责,但我猜它发生在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.