1

I have a typescript object like this:

class myObj {
   public param1,
   public param2,
   public param3
}

In my other object I have an array of that object

class otherObj {
   public arrayOfMyObj:myObj[]

   constructor(){
       this.arrayOfMyObj = [{param1: "value", param2: "value"}]
   }
}

However this code throws an error, because that first item in the JSON array does not match myObj exactly (it is missing param3) if there any way to make it optional or just not to check this? Obviously I would normally just create a new myObj and populate it, however this is a very long, hard coded JSON array.

Ryan Knell
  • 6,204
  • 2
  • 40
  • 32
  • 4
    If you don't call `new myObj()`, then your type is wrong. Typescript isn't being "too helpful", it's doing exactly what it's made for, validating types. – chrisbajorin Jun 30 '16 at 03:34
  • 4
    If you made `myObj` an interface, then you can declare optional fields. It would also better match the fact that you are not calling any constructors here. – Thilo Jun 30 '16 at 03:36

2 Answers2

4

It will looks something like this:

interface IMyObj {
   param1: string;
   param2: string;
   param3?: any;
}


class otherObj {
   public arrayOfMyObj: IMyObj[]

   constructor() {
       this.arrayOfMyObj = [{ param1: "value", param2: "value" }]
   }
}

Note

All class members are public by default.

It is better to specify type of variable. Unspecified type is "any" you willn't be awared about possible errors is case of type checking fails.

TSV
  • 7,538
  • 1
  • 29
  • 37
1

Maybe this answer will help you

One other way is to use Object.assign to extend a valid typed object with the property you only need (omitting property a and c in this example)

export class A {
    a:number=1;
    b:number;
    c:string;
    d:string; }

let validA:A = Object.assign(new A(),{
    b:3,
    d:'Lorem ipsum' 
}); 

I personnaly prefer this syntax to avoid multiline object initialisation and the boring thing to create an interface (so another file quite useless if a coresponding class exists) for each model of my app.

In addition, don't hesitate to set default value in your class definition, even if it's not mandatory for this case.

One last important thing is that you don't loose class methods in this case (opposing to {} casting)

Community
  • 1
  • 1
Nicolas Janel
  • 3,025
  • 1
  • 28
  • 31