![](/img/trans.png)
[英]Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'
[英]Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any>
这段代码:
import * as React from 'react';
const Component = () => <div/>;
function culprit<P>(node: React.ReactElement<P>) {
console.log(node);
}
culprit(<Component/>);
...在使用 TypeScript 编译时产生此编译错误:
错误 TS2345:“Element”类型的参数不可分配给“ReactElement”类型的参数。 类型“null”不可分配给类型“ReactElement”
只有当strictNullChecks TypeScript 编译标志设置为true
时才会发生这种情况。
是的,我可以禁用该标志,但我希望启用它以增加编译时检查/安全性。
如果我将最后一行更改为:
culprit( (<Component/> as React.ReactElement<any>) );
...它适用于设置为true
的标志。
我最近尝试在 React 项目中从“纯”JavaScript 迁移到 TypeScript,这会阻碍我的所有测试,因此将所有 TypeScript 类型断言添加到测试代码中的所有这些事件将是一件痛苦的事情。
这是一个错误,还是我别无选择?
如果您的组件或组件测试文件中有 JSX,则必须将.tsx
作为文件扩展名。 我的代码没有编译,因为我有 .ts 文件扩展名。 我将它重命名为.tsx
/ jsx
那jsx
它开始工作得很好!
另请注意,我使用的是 Typescript,这就是我将其重命名为.tsx
的原因。 如果您使用 ES6, .jsx
其重命名为.jsx
。
这显然是 15.0.5 React 类型定义中引入的一个问题。 如果您更改为 15.0.4,一切都应该没问题。
看到这个问题: https : //github.com/DefinitelyTyped/DefinitelyTyped/pull/14284
当我不在 React Fragment 或空标签中返回 JSX 时,就会发生这种情况。
const ErrorMessage: FC<ErrorProps> = (props) => {
if (!isEmpty(props.errors)) {
return Object.entries(props.errors).map((item) => (
<Typography component="span">{item[0]}</Typography>
))
};
return <></>;
};
当我添加空标签时,一切都按预期工作。
const ErrorMessage: FC<ErrorProps> = (props) => {
if (!isEmpty(props.errors)) {
return (
<>
{Object.entries(props.errors).map((item) => (
<Typography component="span">{item[0]}</Typography>
))}
</>
)
};
return <></>;
};
此外,如果我们删除return <></>
语句,则会显示错误。 正如我所写,组件总是需要返回正确的 JSX 组件。
版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.