给出此界面:
interface Props extends React.HTMLAttributes<HTMLDivElement> {
compLevel: string;
property: Property;
comps: Property[];
}
鉴于property
属性已经以HTMLAttributes
的形式存在于property?: string;
上,因此我遇到了困难:
接口“ Props”错误地扩展了接口 “ HTMLAttributes”。属性“ property”的类型为 不相容。 类型'SerializedObject'不能分配给类型'字符串'。
重命名属性是可行的,尽管我不想这样做。为扩展/使用方法建议使用什么接口,这样我就不需要在className
上重新定义Props
了? / p>
答案 0 :(得分:0)
推荐使用什么界面...,这样我就不必在
className
上重新定义Props
了?
我们倾向于定义这样的类型:
type HasClassName = {
className: string;
};
然后像这样使用它:
type Property = {
foo: string;
bar: string;
};
interface Props extends HasClassName {
compLevel: string;
property: Property;
comps: Property[];
}
答案 1 :(得分:0)
由于HTMLAttribute中已经存在“属性”的属性,因此可以看到三种前进的方法:
答案 2 :(得分:0)
您将与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>
一样对待,而只使用{em}中没有出现的那些属性。因此,这将最终{em>覆盖 PropsExtra
属性,而不是扩展它。
现在将没有错误。
请注意以下内容将是一个错误:
property
由于它们在declare function acceptAttributes(attrs: React.HTMLAttributes<HTMLDivElement>);
declare const p: Props;
acceptAttributes(p); // error! p is not a React.HTMLAttributes<HTMLDivElement>
属性的类型上有所不同(heh),因此类型property
的值不再是有效的Props
值。任何期望后者不会接受前者的东西。然后,您可以更改此类函数的预期参数类型,该参数类型可能会向外层叠,直到此更改触及您的代码库超出预期为止。
因此,这是否真的适合您取决于用例。祝你好运!