接口A错误地扩展了接口B

时间:2019-05-28 15:56:30

标签: reactjs typescript

给出此界面:

interface Props extends React.HTMLAttributes<HTMLDivElement> {
  compLevel: string;
  property: Property;
  comps: Property[];
}

鉴于property属性已经以HTMLAttributes的形式存在于property?: string;上,因此我遇到了困难:

  

接口“ Props”错误地扩展了接口   “ HTMLAttributes”。属性“ property”的类型为   不相容。       类型'SerializedObject'不能分配给类型'字符串'。

重命名属性是可行的,尽管我不想这样做。为扩展/使用方法建议使用什么接口,这样我就不需要在className上重新定义Props了? / p>

3 个答案:

答案 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中已经存在“属性”的属性,因此可以看到三种前进的方法:

  1. 将属性重命名为另一个更精确的术语,该术语与现有属性(例如propsProperty)不重叠
  2. 如果值在某种程度上相似,则可以将该属性转换为SerializedObject以匹配类型签名
  3. 将属性重命名为_property,并将接口的getter和setter设置为从_property而不是property更改。 (尚未对此进行测试)

答案 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中的PropsExtraReact.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值。任何期望后者不会接受前者的东西。然后,您可以更改此类函数的预期参数类型,该参数类型可能会向外层叠,直到此更改触及您的代码库超出预期为止。

因此,这是否真的适合您取决于用例。祝你好运!