首页 > 解决方案 > 如何解决这种类型分配错误(从目标函数到 `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/>?

标签: typescripttypescript-typingsmobxmobx-react

解决方案


如果您查看 , 的类型声明React.StatelessComponentnull则允许但undefined不允许,因此您可以使用null. (如果undefined在运行时也可以工作,您可以考虑向类型提交一个拉取请求以允许它。)


推荐阅读