简体   繁体   English

在打字稿的定义接口中添加属性

[英]Adding property in the defined interface of the typescript

I have two interface define as below.我有两个interface定义如下。

  interface TitleFont{
      fontFamily:string;
      fontStyle:string;
      size:string; \\ need only for the title property.
      opacity:number;
   }
  interface ChartFont{
      fontFamily:string;
      fontStyle:string;
      opacity:number;
   }

Two property in my class is of defined interface type:我的类中的两个属性是定义的接口类型:

 class Chart  {
     title: TitleFont;
     chartTitle: ChartFont;  
  }

Size is the extra property added in TilteFont when compared to ChartFont .大小是增加了额外的属性TilteFont时相比, ChartFont Is there any way to define one interface and make use of it for both the property?有没有办法定义一个接口并将其用于两个属性?

Thanks in advance提前致谢

Would not be a solution here to use inheritance and extend TitleFont from ChartFont这里不是使用继承和从ChartFont扩展TitleFont的解决方案

interface ChartFont{
    fontFamily:string;
    fontStyle:string;
    opacity:number;
}
interface TitleFont extends ChartFont {
    size:string; \\ need only for the tilte property.
}

We still have two interfaces, but in many cases we will be able to work with just a base one (ChartFont) like this我们仍然有两个接口,但在很多情况下,我们将能够使用像这样的基本接口(ChartFont)

var fontSetting1 : ChartFont = Chart.title
var fontSetting2 : ChartFont = Chart.chartTitle
...
// follows common behaviour for ChartFont interface
...

And if later needed, we can up-cast:如果以后需要,我们可以向上转换:

var titleFontSetting : TitleFont = <TitleFont>fontSetting1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM