0

I'm learning Angular and Typescript, I have been doing some small coding but I reached the roof, I can't find a solution for my problem anywhere.

I was able to successfully declare simple types and array of simple types but I'm unable to create an array of objects.

someArray = new Array<ObjectType>();
class ObjectType {
    constructor( name: string, age: number) {
    }
}

and then I try to add element to an array

someArray.push(new ObjectType('John',5) ); 

and get an error:

Duplicate identifier 'someArray'.ts(2300)
Subsequent property declarations must have the same type. Property 'someArray' must be of type 'ObjectType[]', but here has type 'any'.ts(2717)
app.component.ts(10, 3): 'someArray' was also declared here.

How can this be a duplicate? Thank you in advance.


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  someArray = new Array<ObjectType>();
  someArray.push(new ObjectType('John',5) );
}

class ObjectType{
    constructor( name: string, age: number){
    }
}
3
  • You seem to have declared someArray twice Commented Oct 2, 2019 at 20:55
  • 1
    Share you code in app.component.ts as that is where the error seems to originate from. Commented Oct 2, 2019 at 21:04
  • added below ... Commented Oct 2, 2019 at 21:12

1 Answer 1

2

Your syntax is incorrect. In the direct body of the type (class) you can define containing types/fields/methods. In the body of the constructor / methods you can write procedural code you wish to execute. In an angular component it is recommended you always implement the interface OnInit and then write code there you wish to execute when the component loads. ngOnInit executed before the template loads.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  someArray = new Array<ObjectType>();

  ngOnInit() {
    this.someArray.push(new ObjectType('John',5) );
  }
}

Additionally you probably want the args in the constructor to be set on the instance being created. One way you can do that by marking these arguments as public or private depending on the scope you want to give the fields.

class ObjectType{
    constructor(public name: string, public age: number) {
    }
}

You can also add readonly if you do not want the value to be changed after it has been set.

Sign up to request clarification or add additional context in comments.

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.