React & TypeScript HOCs - 为什么我得到 Type '{}' is not assignable to Type P?

React & TypeScript HOCs - why I get Type '{}' is not assignable to Type P?

我在学习使用 TypeScript 学习 React 这本书时遇到了困难。我投降直接从书上复制粘贴代码,编译器还是不爽

我目前的解决方法是提供 'any' 值,而不是 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;

在无效代码中,我收到类型“{}”不可分配给类型 P 错误。我想解决这个问题,因为它可以帮助我了解发生了什么。我是 TypeScript 的新手!

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