claudioz
claudioz

Reputation: 1231

Error with TypeScript syntax: declarative array with methods

I have a problem with TypeScript syntax in my Angular 4 project. If I create a normal class, such as:

export class MyClass {
  field1: string;
  field2: number;
  field3: boolean;

  myMethod() {
   this.field2 = this.field2 + 2;
  }
}

I can't declare an array of MyClass elements with this syntax:

myclassarray: MyClass[] = [{
  field1: 'hello',
  field2: 3,
  field3: false
}];

Because in my class there is an instance method and not a static method. The question is: how can I declare an array of elements that also include non-static methods that are useful to me?

I also don't understand the syntax that allows you to initialize these items in a declarative way.

Upvotes: 0

Views: 97

Answers (3)

msanford
msanford

Reputation: 12227

Since you're using a class, why not use a constructor?

class MyClass {
    constructor(public field1: string, public field2: number, public field3: boolean) {}

    myMethod() {
        this.field2 = this.field2 + 2;
    }

    show() {
        console.log(this.field2);
    }
}

let myclassarray = new MyClass(
    'hello', 3, false
);

You can then call them like so:

myclassarray.myMethod();
myclassarray.show(); // logs 5

Upvotes: 0

Rohan Fating
Rohan Fating

Reputation: 2133

You need to create object of MyClass first and then intialize values then push into array.

myclassarray: Array<MyClass> = [];
myClass: MyClass = new MyClass();
    myClass.field1 ='';
    myClass.field2 =1;
    myClass.field3 = false;


myclassarray.push(myClass);

Upvotes: -1

Saravana
Saravana

Reputation: 40594

You can use Object.assign to assign the object literal to an instance of MyClass:

myclassarray: MyClass[] = [
    Object.assign(new MyClass(), {
        field1: 'hello',
        field2: 3,
        field3: false
    })
];

Upvotes: 3

Related Questions