首页 > 解决方案 > 如何解决错误后续属性声明必须具有相同的类型。角 9

问题描述

我创建了一个类型的类,Posts它具有三个字符串类型的字段,我正在尝试从 Angular 组件类访问它以将三个字段设置为其默认值,但出现以下错误...

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

我的Posts班级代码

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

我如何尝试在 Angular 组件类中设置值的代码

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';
}

标签: angulartypescriptclass

解决方案


你可以...

1)Posts在类中添加一个构造函数,以便在使用new. 在构造函数中使用public访问器将自动将参数声明为可公开访问的属性。

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)AppComponent您可以简单地将类型分配Posts给您的属性并分配值而不使用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',
  };
}

如果必须动态分配对象的值,则必须在函数内部完成。

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';
  }
}

推荐阅读