【问题标题】:an interface may only extend a class or another interface / mapped types一个接口只能扩展一个类或另一个接口/映射类型
【发布时间】:2017-05-29 06:24:01
【问题描述】:

我将typescript 2.1JSX 一起使用,并尝试使用Partial 映射类型来扩展具有所需属性的接口的可选属性的反应组件接口。

这是具有所需属性的接口:

interface ActionsCreators {
  A: string;
  B: string;
};

这是我要扩展的接口:

interface Props extends React.Props<any> {
  C: string;
};

这是映射类型:

type ActionsCreatorsPartial = Partial<ActionsCreators>;

给出这个结果:

type ActionsCreatorsPartial = {
  A?: string;
  B?: string;
}

这是我尝试做的:

interface Props extends React.Props<any>, ActionsCreatorsPartial {
   C: string;
};

但我看到编译错误:“一个接口只能扩展一个类或另一个接口”如何将接口PropsActionsCreatorsPartial 类型连接?

【问题讨论】:

  • 解决方法:type Props = React.Props&lt;any&gt; &amp; ActionsCreatorsPartial &amp; { C: string; };
  • 我认为你的评论应该是答案

标签: reactjs typescript types interface


【解决方案1】:

错误信息是正确的,接口只能扩展其他接口或类的接口,类同样只能实现接口或从另一个类获取接口。

有一个批准的suggestion 允许类实现类型别名,我想如果实现的话,也可以让接口扩展类型别名。

不幸的是,到目前为止,我认为没有任何方法可以将映射类型合并到接口中。

【讨论】:

  • 在理论上我喜欢你的回答,但我需要的是 David Sherret 的实用评论:) 无论如何我都会支持你的回答。
  • @RajabShakiro 谢谢,但您只问如何制作界面,我不知道交叉类型是否适合您的需要。如果您更详细地描述您正在/正在尝试完成的工作,也许您可​​以在这里得到更好的答案
猜你喜欢
  • 2016-12-27
  • 1970-01-01
  • 2015-08-18
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多