类型&#39;元素&#39;的论证不能分配给&#39; ReactElement <any>

时间:2017-02-04 05:50:02

标签: javascript reactjs typescript

此代码:

import * as React from 'react';                                                                                              

const Component = () => <div/>;                                                  

function culprit<P>(node: React.ReactElement<P>) {
  console.log(node);
}

culprit(<Component/>);

...使用TypeScript编译时产生此编译错误:

error TS2345: Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any>'.
  Type 'null' is not assignable to type 'ReactElement<any>

仅当 strictNullChecks TypeScript编译标志设置为true时才会发生这种情况。

是的我可以禁用该标志,但我希望它能够增加编译时检查/安全性。

如果我将最后一行改为:

culprit( (<Component/> as React.ReactElement<any>) );

...它适用于设置为true的标志。

我最近尝试从&#34; plain&#34; React项目中的JavaScript to TypeScript,这使我的所有测试都瘫痪,因此在测试代码中将所有TypeScript类型断言添加到所有这些实例中将会非常痛苦。

这是一个错误,还是我别无选择?

2 个答案:

答案 0 :(得分:8)

这显然是15.0.5 React类型定义中引入的问题。如果你改为15.0.4,一切都应该没问题。

请参阅此问题:https://github.com/DefinitelyTyped/DefinitelyTyped/pull/14284

答案 1 :(得分:0)

对我来说,这个问题是我在艰难时期后发现的其他问题。

如果组件或组件测试文件中的JSX必须具有.tsx扩展名。我的测试或代码正在编译,因为我将其保存为.ts文件。

还请注意,我使用的是Typescript,这就是为什么如果您使用ES6将其重命名为.jsx的原因,我将其重命名为.tsx

相关问题