0

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.

3
  • What's stopping you from using a static method? Commented Sep 7, 2017 at 12:46
  • because I want methods that modify the data fields of my class instance Commented Sep 7, 2017 at 12:47
  • Is it language issue or your problem not understanding principles of OOP? If you need array of objects with methods - you maust use new MyClass() syntax. If you want to initialize properties - use constructor. If you have "too many" properties - use constructor that accepts interface (constructor(dto: MyClassInterface){ this = Object.assign({}, dto);}). Commented Sep 7, 2017 at 12:52

3 Answers 3

3

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
    })
];
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.