这是我的代码:
import { observer } from 'mobx-react';
...
const Widget = observer(() => conditionA ?
<MyCustomWidget ... />
: undefined);
基本上这个想法是,如果conditionA
是真的,我希望Widget
是MyCustomWidget
的一个实例,否则它应该没有。
但是,typescript会引发此错误消息:
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/>
?
如果你看看type declaration of React.StatelessComponent
,null
是允许的,但undefined
不是,所以你可以使用null
。 (如果undefined
也在运行时工作,你可以考虑向打字提交拉取请求以允许它。)