你打算如何处理Props?您可能不应该在需要 React.HTMLAttributes<HTMLDivElement> 的地方使用它。如前所述,并将代码视为complete 示例,我可能会这样定义Props:
// SimpleSpread<L, R> is a simplified version of what happens when you
// do an object spread like {...left, ...right} where left is of type L and
// right is of type R. It is the type R, with any properties on L that
// don't exist in R. (It doesn't work if a key in L is an optional property in
// R, which is why this is simplified)
type SimpleSpread<L, R> = R & Pick<L, Exclude<keyof L, keyof R>>;
// Define the props you want to spread into React.HTMLAttributes<HTMLDivElement>
interface PropsExtra {
compLevel: string;
property: Property;
comps: Property[];
}
// Define Props
interface Props
extends SimpleSpread<React.HTMLAttributes<HTMLDivElement>, PropsExtra> {}
这通过将Props 视为PropsExtra 仅使用来自React.HTMLAttributes<HTMLDivElement> 的那些不出现在PropsExtra 中的属性来工作。所以这最终会覆盖 property 属性,而不是扩展它。
现在没有错误了。
请注意,以下将是一个错误:
declare function acceptAttributes(attrs: React.HTMLAttributes<HTMLDivElement>);
declare const p: Props;
acceptAttributes(p); // error! p is not a React.HTMLAttributes<HTMLDivElement>
由于property 属性的类型不同(呵呵),Props 类型的值不再是有效的React.HTMLAttributes<HTMLDivElement> 值。任何期望后者的东西都不会接受前者。然后,您可以更改此类函数的预期参数类型,这可能会向外级联,直到此更改涉及的代码库超出您的预期。
所以这真的取决于你的用例是否适合你。祝你好运!