2

I'm quite new to Typescript so I imagine this is a pretty stupid question, but I have an array of JSON objects that I want to map to a Panel class.

When my PanelsService class is instantiated I also want to instantiate my array of Panel objects.

What I've got so far:

PanelsService.ts

import {Panel} from './panel';

declare var _: any;

export class PanelsService {

  public panels: Array<Panel>;
  public customPanels: Array<Panel>;

  constructor(private _http:Http) {
    this.panels = window['panels']['views'];
  }
}

From this, none of my Panels are being instantiated (I have a log in the constructor). Obviously I could loop over window['panels']['views'] and do something like this.panels.push(new Panel(myPanel) but it seems like there must be a better way.

FWIW, my Panel class is just a load of properties and a constructor.

garethdn
  • 12,022
  • 11
  • 49
  • 83

1 Answers1

2

If datas inside window['panels']['views'] are an array of Panel, you just need to cast it to make TypeScript happy:

this.panels = <Panel[]>(window['panels']['views']);

This will not changed anything for the generated javascript, but it will compile.
Note that it will never call the Panel constructor. Your object in window['panels']['views'] are already instanciate, so it's just a cast.

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • Is there some kind of pattern I'm missing then if I want to instantiate a bunch of classes from JSON, apart from looping and pushing? It seems like that would be a fairly common use case - for example, when i instantiate the class I want to store an object on the instance that contains the original property values. – garethdn Dec 22 '15 at 15:13
  • A JSON is a javascript object. It has been 'sort of' instanciated. If it looks like your desired object, you don't need to do much. You can always instanciate your own objects base on the JSON data if you need to, but it will require manual mapping yes. You can use function like .map() and .filter() if you don't want to push and loop. – Cyril Gandon Dec 22 '15 at 15:20