【发布时间】:2021-06-23 13:19:14
【问题描述】:
我有一个 TS 问题,代码的 JS 版本可以工作,但我无法获得要编译的类型。
我试图为这个问题简化它。希望我没有删除太多会对答案产生影响的内容。
因此,简化后,我正在尝试编写一个组件<Set>,它将另一个组件作为道具,并将其包裹在<Set> 的子代周围。此外,我希望传递给 <Set> 的所有道具都传递给作为道具传递的组件。
这是代码
import React, { ReactElement, ReactNode } from "react";
interface WtProps {
children: ReactNode;
}
type WrapperType<WTProps extends WtProps> = (
props: WTProps
) => ReactElement | null;
interface SetProps<P extends WtProps> {
wrap: WrapperType<P>;
children: ReactNode;
[x: string]: unknown;
}
export function Set<WProps extends WtProps>(props: SetProps<WProps>) {
const { wrap, children, ...rest } = props;
return React.createElement(wrap, rest, children);
}
interface WrapperProps {
children: ReactNode;
foo: string;
}
const ChildWrapper: React.FC<WrapperProps> = ({ foo, children }) => {
return (
<div>
<h1>ChildWrapper</h1>
<p>{foo}</p>
{children}
</div>
);
};
export default function App() {
return (
<Set<WrapperProps> wrap={ChildWrapper} foo="value">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some happen!</h2>
</Set>
);
}
这是一个代码框链接:https://codesandbox.io/s/musing-feynman-3euuu?file=/src/App.tsx
我尝试了很多不同的解决方案,但这就是我现在所拥有的。我得到的错误是rest参数
return React.createElement(wrap, rest, children);
它说
No overload matches this call.
The last overload gave the following error.
Argument of type '{ [x: string]: unknown; }' is not assignable to parameter of type 'Attributes & WProps'.
Type '{ [x: string]: unknown; }' is not assignable to type 'WProps'.
'WProps' could be instantiated with an arbitrary type which could be unrelated to '{ [x: string]: unknown; }'.ts(2769)
index.d.ts(292, 14): The last overload is declared here.
我已阅读此问题+答案How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?,所以我想我知道为什么会出现错误,但我不知道该怎么办。
我需要更改什么才能使其编译?
编辑:我可以通过将wrap 属性设为any 类型来“修复”它,但我不想这样做。我想要更严格的类型。但无论如何,这里是any https://codesandbox.io/s/pedantic-nobel-x790n
【问题讨论】:
标签: reactjs typescript generics