反应&TypeScript HOCs - 为什么我得到 Type '{}' 不能分配给 Type P?
[英] React & TypeScript HOCs - why I get Type '{}' is not assignable to Type P?
本文介绍了反应&TypeScript HOCs - 为什么我得到 Type '{}' 不能分配给 Type P?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用 TypeScript 学习 React 一本书进行编码时,我碰壁了.我投降了,直接从书上复制粘贴的代码,但是编译器还是不爽
我目前的解决方法是提供任何"值,而不是 IProps,但这是一个廉价的黑客.
不工作的代码:
import * as React from 'react';接口 IProps {加载:布尔值;}const withLoader = <P extends object>(组件:React.ComponentType<P>): React.FunctionComponent=>({ 加载, ...道具}:IProps) =>加载?(<div className="loader-overlay"><div className="loader-circle-wrap"><div className="loader-circle"/>
) : (<组件{...道具}/>);导出默认 withLoader;
工作代码(我只将 IProps 更改为 any):
import * as React from 'react';接口 IProps {加载:布尔值;}const withLoader = <P extends object>(组件:React.ComponentType<P>): React.FunctionComponent=>({ 加载, ...道具}:任何) =>加载?(<div className="loader-overlay"><div className="loader-circle-wrap"><div className="loader-circle"/>
) : (<组件{...道具}/>);导出默认 withLoader;
在不工作的代码中,我得到类型{}"不可分配给类型 P 错误.我想解决这个问题,因为它可以帮助我了解正在发生的事情.我完全是 TypeScript 的初学者!
解决方案
从 3.2 开始 泛型扩展运算符的行为已经改变.显然, props
的类型作为一个负面影响被删除了,但是你可以通过使用 {...props as P 将它转换回 P
来解决这个问题}
当传播回包装的组件时.
I hit the wall while coding along with Learning React with TypeScript book. I surrendered and copy pasted code directly from the book, but compiler is still unhappy
My current workaround is to provide 'any' value, instead of IProps, but this is a cheap hack.
Not working code:
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;
Working code (I only changed IProps to 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;
In not working code, I get Type '{}' is not assignable to Type P error. I would like to solve this issue, as it would help me understand what is going on. I am total beginner at TypeScript!
解决方案
Starting with 3.2 the behaviour of the spread operator for generics has changed. Apparently the type of props
gets erased as a negative side effect, but you can work around that by casting it back to P
using {...props as P}
when spreading back into the wrapped component.
这篇关于反应&TypeScript HOCs - 为什么我得到 Type '{}' 不能分配给 Type P?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!