如何解决这种类型赋值错误(从目标函数到`观察')?

问题描述 投票:0回答:1

这是我的代码:

  import { observer } from 'mobx-react';

  ...

  const Widget = observer(() => conditionA ?
      <MyCustomWidget ... />
      : undefined);

基本上这个想法是,如果conditionA是真的,我希望WidgetMyCustomWidget的一个实例,否则它应该没有。

但是,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/>

typescript typescript-typings mobx mobx-react
1个回答
0
投票

如果你看看type declaration of React.StatelessComponentnull是允许的,但undefined不是,所以你可以使用null。 (如果undefined也在运行时工作,你可以考虑向打字提交拉取请求以允许它。)

© www.soinside.com 2019 - 2024. All rights reserved.