如何正确键入带有Typescript的React HOC

问题描述

我是Typescript的新手,我无法弄清楚如何用它正确键入HOC。我已经花了一整天时间来解决这个问题,但没有成功。我有一个非常基本的代码片段,其中包含BaseComponent和一个简单的HOC。由于某些原因,在创建BaseComponent时,出现Typescript错误:

Type '{ total: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{},ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'. Property 'total' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{},ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'

您知道如何正确设置道具类型吗?

BaseComponent:

interface SummaryProps {
    sum: number;
}

class Summary extends React.Component<SummaryProps> {
    render() {
        return (
            <div>{this.props.sum}</div>
        );
    }
}

export default withMyHOC(Summary);

HOC:

interface WithMyHOCProps {
    total: number;
}

const withMyHOC = (WrappedComponent: React.ComponentType<any>): React.ComponentClass => {
    return class extends React.Component<WithMyHOCProps> {
        render() {
            return (
                <WrappedComponent
                    {...this.props}
                    sum={this.props.total + 1}
                />
            );
        }
    };
};

export default withMyHOC;

初始化:

import Summary from 'features/Summary.tsx';

<Summary total={5} /> // here I am getting Typescript error described above

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)