【问题标题】:React & TypeScript HOCs - why I get Type '{}' is not assignable to Type P?React & TypeScript HOCs - 为什么我得到 Type '{}' is notassignable to Type P?
【发布时间】:2019-07-01 23:43:46
【问题描述】:

我在编写《Learning React with TypeScript》这本书时碰壁了。我投降并直接从书中复制粘贴的代码,但编译器仍然不满意

我目前的解决方法是提供“任何”值,而不是 IProps,但这是一种廉价的 hack。

不工作的代码:

import * as React from 'react';

interface IProps {
  loading: boolean;
}

const withLoader = <P extends object>(
  Component: React.ComponentType<P>
): React.FunctionComponent<P & IProps> => ({ loading, ...props }: 
IProps) =>
  loading ? (
    <div className="loader-overlay">
      <div className="loader-circle-wrap">
        <div className="loader-circle" />
      </div>
    </div>
  ) : (
    <Component {...props} />
  );

 export default withLoader;

工作代码(我只将 IProps 更改为 any):

import * as React from 'react';

interface IProps {
  loading: boolean;
}

const withLoader = <P extends object>(
  Component: React.ComponentType<P>
): React.FunctionComponent<P & IProps> => ({ loading, ...props }: 
any) =>
  loading ? (
    <div className="loader-overlay">
      <div className="loader-circle-wrap">
        <div className="loader-circle" />
      </div>
    </div>
  ) : (
    <Component {...props} />
  );

 export default withLoader;

在不工作的代码中,我得到 Type '{}' is not assignable to Type P 错误。我想解决这个问题,因为它可以帮助我理解发生了什么。我是 TypeScript 的初学者!

【问题讨论】:

    标签: reactjs typescript types react-props higher-order-components


    【解决方案1】:

    从 3.2 开始,behaviour of the spread operator for generics has changed。显然,props 的类型会作为负面影响被删除,但您可以通过在传播回包装组件时使用 {...props as P} 将其转换回 P 来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 2022-01-26
      • 2022-11-18
      相关资源
      最近更新 更多