角度:“对象”类型可分配给很少的其他类型

时间:2019-09-30 13:35:29

标签: angular

我有这段代码可以在Angular 5中正常工作,但是我正在尝试更新到Angular 8:

  this.awsService.getProfiles().subscribe(profiles => {
    this.profiles = profiles;
    if (this.profiles.length > 0 && this.profiles.indexOf(this.currentProfile) == -1) {
      this.currentProfile = this.profiles[0];
      localStorage.setItem('profile', this.currentProfile);
    }
  }, err => {
    this.profiles = [];
  })

我收到此错误:

ERROR in app/app.component.ts:85:9 - error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
  Type 'Object' is missing the following properties from type 'string[]': length, pop, push, concat, and 26 more.

85         this.profiles = profiles;

Angular 8中正确的语法是什么?

2 个答案:

答案 0 :(得分:1)

您可以为配置文件定义类型或接口,而不必使用Object,它非常通用,不会帮助您过多地了解数据的结构(它仅具有JS通用Object的属性,例如{{ 1}}和toString)。

haveOwnProperty

如果export type Profiles = { property1: string; property2: number; // ... } // OR export interface Profiles { property1: string; property2: number; // ... } 已经具有返回类型,this.awsService.getProfiles()似乎应该让TypeScript自动声明该类型或定义一个等于string[]的类型Profiles:< / p>

string[]

或直接告诉Typescript export type Profiles = string[]; // ... public profiles: Profiles; 具有this.profiles类型:

string[]

答案 1 :(得分:0)

  

我有这段代码可以在Angular 5中正常工作,但是我正在尝试更新到Angular 8:

在升级过程中,Rxjs从版本5更改为版本6。这一更改对TypeScript处理类型的方式产生了影响,因为版本6在推断类型方面做得更好。

this.awsService.getProfiles().subscribe(....)

从Angular 5到Angular 6之间的一大变化是从HttpModule到新的HttpClientModule的切换,并且该模块引入了序列化的JSON支持。

例如;

  function getProfiles() {
     return this.http.get<MyInterfaceType>(....);
  }

在上面,GET请求会将JSON对象反序列化为接口类型MyInterfaceType

完成自动升级后,不会直接将此功能添加到您的源代码中。因此,您可能有一些像这样的旧样式代码。

   function getProfiles() {
       return this.http.get(....);
   }

这为TypeScript带来了许多类型挑战。

  • 该函数没有声明的返回类型,必须对其进行推断
  • http.get()的返回类型是Observable<Response>类型,而不是JSON类型
  

我收到此错误:

该错误与模棱两可的Object类型有关这一事实意味着您尚未更新awsService()的代码以正确使用新的HttpClientModule,并且尚未定义getProfiles()的正确返回类型。

这里有几种方法:

  • getProfiles(): Observable<any[]>定义返回类型以使错误消失,但这可能无法提供可运行的代码。
  • 通过将类型定义为http.get<Profile[]>(...)作为示例,更新HTTP以序列化为JSON对象
  • subscribe((profiles: any[]) => {...})定义参数类型

无论哪种方式,我都认为升级不会一路走来。

尝试使单元测试正常运行,然后尝试使整个应用程序运行,会更容易。虽然您可以使某些TypeScript错误静音。从问题上还不清楚这是代码的症状,升级问题还是只是类型不匹配。