Home > Net >  Is there a simple way to switch between 2 models in Angular 2?
Is there a simple way to switch between 2 models in Angular 2?

Time:09-28

I have problem with models in Angular 2. I have 2 models:

interface Model1 {
  id: number;
  name: string;
  size: string;
  count: number;
  children: Model2[];
}

interface Model2 {
  id: number;
  parentId: number
  title: string;
  subtitle: string;
  publisher: string;
}

I am binding some data with variable by id but there are cases that I use Model1 and sometimes Model2. If I am trying to declare it with 2 models but it is not working. Is there any way to do that instead of using 'any'? I try to do something like that:

private exampleVaraible: Model1 || Model2;

CodePudding user response:

the correct syntax to declare a variable with two type definitions is :

private exampleVaraible: Model1 | Model2;

this.exampleVaraible now can be assigned values like

this.exampleVaraible = { id: 12121, subtitle: '232323', parentId: 2323, publisher: '2323', title: '2323' };

this.exampleVaraible = { id: 1121212, name: '22323', size: '2323', count: 2323, children: [ { id: 12121, subtitle: '232323', parentId: 2323, publisher: '2323', title: '2323' }]

  • Related