Rinzler21
Rinzler21

Reputation: 476

How can i solve the error Subsequent property declarations must have the same type. Angular 9

I've created a class of type Posts which has three fields of type string and I'm trying to access it from an Angular component class to set the three fields to their default values but I get the following error...

Subsequent property declarations must have the same type.  
Property 'post1' must be of type 'Posts', but here has type 'any'

Code of my Posts class

export class Posts{
    Key:string;
    Email:string;
    Password:string;
}

Code of how I'm trying to set the values in my Angular component class

export class AppComponent {
  title = 'proyecto-nro2';

  post1 = new Posts();
//Said the error above in every post1.
  post1.Key = 'NONE';
  post1.Email = 'NONE';
  post1.Password = '2';
}

Upvotes: 2

Views: 5560

Answers (2)

j3ff
j3ff

Reputation: 6099

You can either ...

1) Add a constructor to the Posts class to assign values when creating the object with new. Using the public accessor in the constructor will automatically declare the parameters as publicly accessible properties.

export class Posts {
  constructor(
    public key: string,
    public email: string,
    public password: string,
  ) { } 
}

export class AppComponent {
  // order of the parameters matters here
  // as it matches the order in the class constructor
  post1 = new Post('NONE', 'NONE', '2');
}

2) In the AppComponent you can simply assign the type Posts to your property and assign value without using new.

export class Posts {
  key: string;
  email: string;
  password: string;
}

export class AppComponent {
  // order of the properties doesn't matter here
  // as long as the properties exist and match the type
  post1: Posts = {
    key: 'NONE',
    email: 'NONE',
    password: '2',
  };
}

If the value of the object have to be assign dynamically, this has to be done inside functions.

export class Posts {
  key: string;
  email: string;
  password: string;
}

export class AppComponent implements OnInit {
  post1 = new Posts();

  ngOnInit() {
    post1.key = 'NONE';
    post1.email = 'NONE';
    post1.password = '2';
  }
}

Upvotes: 1

rickz
rickz

Reputation: 4474

If you are going to use a class, then look at https://www.typescriptlang.org/docs/handbook/classes.html
and you could write your code similar to the following.

    export class Posts{
    key:string;
    email:string;
    password:string;
    constructor(key:string, email:string, password:string){
        this.key = key;
        this.email = email;
        this.password = password;
    }
}

and in your component class

    post1: Posts = new Posts('NONE', 'NONE', '2');

Upvotes: 0

Related Questions