Reputation: 97
* I really dont know and dont understand why this is happening, im new using Angular *
ErrorSubsequent property declarations must have the same type. Property 'post1' must be of type 'Posts', but here has type 'any'
and Duplicate identifier 'post1'
Post class
export class Posts{
Key:string;
Email:string;
Password:string;
}
AppComponent class where i use the post 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: 3
Views: 1953
Reputation: 719
As @nayakam said you should set the properties in the constructor of your Posts object
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;
}
}
The problem with this is that it can become annoying if some parameters are optionals, for me the best syntax is to send an object to initialize your models and export an interface so that your AppComponent knows what the Posts constructor needs as input
export interface IPosts {
key: string;
email: string;
password: string;
}
export class Posts{
key: string;
email: string;
password: string;
constructor(inputData: IPosts) {
this.key = inputData.key;
this.email = inputData.email;
this.password = inputData.password;
}
}
export class AppComponent {
title = 'proyecto-nro2';
post1: Posts = new Posts({
key: 'NONE',
email: 'NONE',
password: '2'
});
}
Upvotes: 1
Reputation: 4251
Properties can't initialised directly on a class in ES6. Initialise the post object inside the constructor and set the properties.
export class AppComponent {
title = 'proyecto-nro2';
post1: Posts;
constructor(){
this.post1 = new Posts();
this.post1.Key = 'NONE';
this.post1.Email = 'NONE';
this.post1.Password = '2';
}
}
Other Option:
class Posts {
Key: string;
Email: string;
Password: string;
constructor(key: string, email: string, password: string) {
this.Key = key;
this.Email = email;
this.Password = password;
}
}
export class AppComponent {
title = 'proyecto-nro2';
post1: Posts = new Posts('NONE', 'NONE', '2');
}
Upvotes: 3