【问题标题】:Cannot assign types to a React High Order Component无法将类型分配给 React 高阶组件
【发布时间】:2021-04-17 18:16:12
【问题描述】:

我需要创建一个 HOC,它采用一个组件并返回一个采用扁平化道具的新组件(我正在使用 flat 来实现它)并将未扁平化的道具应用到原始组件。

没有类型的 HOC 看起来像这样(我已经对其进行了测试,它按预期工作):

const HOC = (Component) => (props) => {
    const newProps = unflatten(props);

    return <Component {...newProps} />;
};

问题是现在我需要向它添加类型,所以这是我认为应该工作的:

const HOC = (Component: React.ComponentType) => (props: { [key: string]: string; }) => {
    const newProps = unflatten(props);

    return <Component {...newProps} />;
};

此解决方案导致最终返回行出现此错误

Type 'unknown' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Type 'unknown' is not assignable to type 'IntrinsicAttributes'.ts(2322)

【问题讨论】:

    标签: reactjs typescript typeerror high-order-component


    【解决方案1】:

    您可以执行以下操作

    const newProps = unflatten(props) as { [key: string]: string; };
    

    const newProps = unflatten(props) as  any;
    

    【讨论】:

    • 结合这个类型和你的建议使它工作:) type IProps = { [key: string]: string; }; type IHOC = (Component: React.ComponentType) => (props: IProps) => JSX.Element;
    猜你喜欢
    • 2019-07-25
    • 2020-05-01
    • 1970-01-01
    • 2019-07-01
    • 2021-06-30
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多