【发布时间】:2017-06-21 13:51:07
【问题描述】:
这段代码:
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 的标志。
我最近尝试在一个 React 项目中从“普通”JavaScript 迁移到 TypeScript,这会导致我的所有测试出错,因此将所有 TypeScript 类型断言添加到测试代码中的所有这些事件中会很痛苦。
这是一个错误,还是我别无选择?
【问题讨论】:
标签: javascript reactjs typescript