打字稿的“追加”语法

时间:2018-09-24 11:12:12

标签: typescript

我正在Angular打字稿环境中工作。我通过HTTP获得了一个不错的JSON对象,它很好地映射到ResultViewPlotCfg结构:

export class ResultViewPlot {
  cfg: ResultViewPlotCfg
  data: ResultViewPlotData
}

export class ResultViewPlotCfg{
  y_parameter: string;
  x_parameter?: string;
  y_title?: string;  
  x_title?: string;  
  y_max?: number;
  y_min?: number;
}

export class ResultViewPlotData 
{
  pom?: number[][];
  ref?: number[][];
  res?: number[][];
}

我需要将其转换为PlotlyGraph结构,如下所示:

class PlotlyGraph {
  data : [ 
    {x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}}, 
    {x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}},
    {x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}}
  ];
  layout : { 
    yaxis?: {title?:string, range?:number[] },
    margin?: {l?:number, r?:number, t?:number, b?:number }
  };
}

我的翻译是在PlotlyGraph结构的构造函数中完成的,如下所示:

  constructor( plot : ResultViewPlot)
  {
    this.data = 
    [
      {x: plot.data.ref[0], y: plot.data.ref[1], type:'scatter', mode:'lines', name:'ref', line:{color:'blue', dash:'solid'} },
      {x: plot.data.res[0], y: plot.data.res[1], type:'scatter', mode:'lines', name:'sim', line:{color:'green', dash:'longdash'} },
      {x: plot.data.pom[0], y: plot.data.pom[1], type:'scatter', mode:'lines', name:'pom', line:{color:'grey', dash:'dashdot'} }
    ]
    this.layout = { 
      yaxis: {
        title: plot.cfg.y_title,
        range: [plot.cfg.y_min, plot.cfg.y_max]
      }, 
      margin:{l:50, r:20, t:10, b:40} 
    };
  }

问题:plot.cfg.y_min可能不存在

我现在的窍门是y_maxy_min可能不存在。这意味着如果它们存在于PlotlyGraph中,则仅应在ResultViewPlotCfg中进行设置。但是我不知道实现该目标的语法是什么。

我尝试过:

if (plot.cfg.y_max && plot.cfg.y_min) {
  this.layout.yaxis.range = [plot.cfg.y_min, plot.cfg.y_max];
}

但是我似乎无法输入if语句。即使我这样做,我怀疑它会删除this.layout.yaxis.title而不是对其进行扩充。将新数据添加到现有结构的正确语法是什么?

0 个答案:

没有答案