javascript - 在 Typescript 中使用 React Props 的传播运算符(错误:...可以用不同的约束子类型 {} 实例化)
问题描述
我正在尝试使用接收道具的 Typescript 在 React 中编写一个高阶组件,“消耗”其中一个,然后将其余部分传递给子组件。
function testConnect<T>(Child: React.ComponentType<T>): React.ComponentType<T> {
type InitialState = {
iS: StoreShape.State;
};
type LAP = InitialState & T;
const Connector = (props: LAP) => {
const { iS, ...rest } = props;
// do something with iS
return (
<Child // Visual Studio complains about this line.
{...rest}
/>
);
};
return Connector;
}
但是,这失败并出现错误:'Pick<LAP, Exclude<keyof T, "iS">>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'
我不仅想知道我是否能做些什么,而且还想知道为什么会发生这种情况。
解决方案
实际上,Typescript 遇到了您的组件的问题:
const Component = testConnect(({ iS }) => <div>{iS}</div>);
<Component iS={...} />
所以你要么必须
(a) 将所有道具(而不仅仅是休息)传递给组件。
<Child {...props} />
iS
(b) 通过从 T中排除键,确保不能传入名为“iS”的任何道具:
testConnect<T>(Child: React.ComponentType<Omit<T, "iS">>>): React.ComponentType<T> {
推荐阅读
- c - make:系统找不到指定的文件(错误2)
- python - 无法停止 ThreadPoolExecutor
- mongodb - Docker 容器中的 MongoDB
- c# - C# 打卡 / 时钟小时 - 总工作时间
- r - 一次引入多个文件时,R仅输出最后一个文件的数据
- ios - HTML Drop Down 未在 iPhone 的 IOS 13 中选择选项
- php - 警告:mysqli_stmt_bind_result():绑定变量的数量与准备好的语句中的字段数量不匹配
- javascript - 检测操作系统并重定向到安装的移动应用程序
- flutter - 如何在颤动中将 InputText 转换为 Text Widget
- swift - 来自推送视图控制器的字段为零