从 MobX Provider 转移到 React 上下文,typescript 问题

Moving from MobX Provider to React context, typescript issue

正在尝试从 mobx 的提供者转移到 React 上下文。 我已经检查了这篇文章,它非常适合我想要的 https://shevchenkonik.com/blog/react-typescript-mobx

我的用例包括一个注册表对象,它包含商店和服务,需要通过使用 React 上下文将其传递给组件。

我让它工作了 99%,但是打字稿让我很难过。 下面是一个 link 的示例。我将所有内容都放在 2 个文件中以使其更容易

https://codesandbox.io/s/minimal-observer-forked-sd88n

虽然 UI 被渲染了,但 TS 抱怨包装组件没有传递第 53 行的道具(由 HOC 传递)。

任何帮助将不胜感激 谢谢

这种方法在 TS 上效果不是很好,这就是为什么作者“巧妙地”在他尝试使用它的实际示例中省略了类型:

@withStore
@observer
class UserNameComponent extends Component< ??? > {
    render() {
        // props are completely untyped here
        const { store } = this.props;
        return (
            <div>{store.userStore.name}<div>
        )
    }
}

您可以做的是将属性标记为可选,然后使用空断言运算符 ! 让 TS 跳过空检查:

@withStore
@observer
class UserNameComponent extends Component<{ store?: Store }> {
    get store() {
       return this.props.store!
    }

    render() {
        return (
            <div>{this.store.userStore.name}<div>
        )
    }
}

显然它不是超级类型安全的,因为如果你忘记用装饰器包装你的组件,它就会抛出。这就是为什么函数式组件在这种情况下更好更容易使用的原因。