typescript - 如何解决这种类型分配错误(从目标函数到 `observe` )?
问题描述
这是我的代码:
import { observer } from 'mobx-react';
...
const Widget = observer(() => conditionA ?
<MyCustomWidget ... />
: undefined);
基本上这个想法是,如果conditionA
是真的,我希望Widget
是 的一个实例
MyCustomWidget
,否则它应该什么都不是。
但是打字稿会引发此错误消息:
Error:(25, 26) TS2345: Argument of type '() => Element | undefined' is not assignable to parameter of type 'IReactComponent<any>'.
Type '() => Element | undefined' is not assignable to type 'ClassicComponentClass<any>'.
Type '() => Element | undefined' provides no match for the signature 'new (props: any, context?: any): ClassicComponent<any, ComponentState>'.
如果我更改undefined
为<div />
,那么它可以工作。
但是,完全可以避免使用<div/>
?
解决方案
如果您查看 , 的类型声明React.StatelessComponent
,null
则允许但undefined
不允许,因此您可以使用null
. (如果undefined
在运行时也可以工作,您可以考虑向类型提交一个拉取请求以允许它。)
推荐阅读
- android - gRPC Android DEADLINE_EXCEEDED 但未向服务器发出请求
- python - 让python控制台在Windows任务栏中闪烁
- python - 在 Plotly 中创建具有多个标题和字幕轴的图形
- sql - 查询优化器是否能够从 WHERE 子句中提取有效常量以避免重复评估?
- javascript - 使用 AJAX POST/GET 方法解析 Base64 字符串时的未定义索引
- jquery - 有条件的切换类
- c# - 如果我不能在 C# 中调用析构函数,为了安全起见销毁对象的解决方案是什么?
- java - 滚动窗格中的 TextField 未正确显示
- macos - 如何使用 IOHIDManager 或蓝牙读取 iOS 键盘上的 home 键?
- php - incIude.php,在“l”位置用大写“i”拼写