打字稿:通用反应组件上儿童的类型推断

时间:2017-08-05 22:00:28

标签: reactjs typescript

给定一个在两个属性上是通用的react组件,一个var result = dbContext.Customers .Where(c => c.Name == "Mostafa") .AsEnumerable() .Where(c => c.Age == 18) .ToList(); 函数返回类型load,以及子节点(它是一个带有类型T参数的单个函数)。 ..

T

typescript无法从class Test<T> extends React.Component<{ load: () => T; children: (r: T) => JSX.Element; }> { render() { return this.props.children(this.props.load()); } } 的返回值推断res的类型,默认为load类型。

{}

这是一个错误,还是打字稿不能根据返回值推断 - 因为它看起来像支持键入JSX子项。

编辑:

对于后台,用例正在创建一个“懒惰”组件,该组件接受<Test load={() => ({ test: 'x' })}> {res => <span> {res.test} </span>} </Test>; 函数,该函数返回一个解析为某些JSX的承诺。

1 个答案:

答案 0 :(得分:2)

更新:与此同时,TypeScript得到了改进,因此问题中给出的代码会自动推断出int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res); int char_to_int(char* value, int *res) { // do something } 的类型。我没有检查哪个更改对此负责,但我猜它发生在3.0-3.3附近。

我认为问题在于您的代码被转换为类似于:

的内容
res

从这种情况可以更清楚地看出,编译器/定义很难正确推断泛型参数。在你的情况下,提示编译器就足够了:

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