【发布时间】: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