gpt4 book ai didi

javascript - 类型 'Element' 的参数不可分配给类型为“ReactElement”的参数

转载 作者:可可西里 更新时间:2023-11-01 02:39:20 25 4
gpt4 key购买 nike

这段代码:

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 toparameter of type 'ReactElement'. Type 'null' is not assignableto type 'ReactElement

这仅在 strictNullChecks TypeScript 编译标志设置为 true 时发生。

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

如果我将最后一行更改为:

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

...它与设置为 true 的标志一起使用。

我最近尝试在一个 React 项目中从“纯”JavaScript 迁移到 TypeScript,这使我的所有测试都失败了,因此将所有 TypeScript 类型断言添加到测试代码中的所有这些事件将是一件痛苦的事情。

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

最佳答案

如果您的组件或组件测试文件中有 JSX,则必须有 .tsx作为您的文件扩展名。我的代码没有编译,因为我有 .ts 文件扩展名。当我将其重命名为 .tsx/jsx 时,它开始运行良好!

另请注意,我使用的是 Typescript,因此我将其重命名为 .tsx。如果您使用的是 ES6,请将其重命名为 .jsx

关于javascript - 类型 'Element' 的参数不可分配给类型为“ReactElement<any>”的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42036992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com