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

Lui*_*sio 2 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 = [];
  })
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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;
Run Code Online (Sandbox Code Playgroud)

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

Rea*_*lar 12

我有一段在 Angular 5 中运行良好的代码,但我正在尝试更新到 Angular 8:

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

this.awsService.getProfiles().subscribe(....)
Run Code Online (Sandbox Code Playgroud)

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

例如;

  function getProfiles() {
     return this.http.get<MyInterfaceType>(....);
  }
Run Code Online (Sandbox Code Playgroud)

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

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

   function getProfiles() {
       return this.http.get(....);
   }
Run Code Online (Sandbox Code Playgroud)

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

  • 该函数没有声明的返回类型,它必须被推断
  • 的返回类型http.get()是一个Observable<Response>类型而不是 JSON 类型

我收到此错误:

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

这里有几种方法:

  • 定义一个返回类型以getProfiles(): Observable<any[]>消除错误,但这可能不会为您提供可运行的代码。
  • 以定义类型为例http.get<Profile[]>(...),更新 HTTP 序列化为 JSON 对象
  • 定义参数类型 subscribe((profiles: any[]) => {...})

无论哪种方式,我认为您的升级并没有完全到位。

尝试让您的单元测试工作更容易,然后尝试让您的整个应用程序运行。虽然您可以消除其中一些 TypeScript 错误。从问题中不清楚这是代码的症状、升级问题还是只是类型不匹配。


Gui*_*ume 1

您可以为您的配置文件定义一个类型或接口,而不是使用Object它,它非常通用,并且不会帮助您理解数据的结构(它只有 JS 通用对象的属性,例如toStringhaveOwnProperty)。

export type Profiles = {
  property1: string;
  property2: number;
  // ...
}

// OR

export interface Profiles {
  property1: string;
  property2: number;
  // ...
}
Run Code Online (Sandbox Code Playgroud)

如果this.awsService.getProfiles()已经有一个返回类型,string[]那么似乎您应该让 TypeScript 自动断言该类型或定义一个Profiles等于的类型string[]

export type Profiles = string[];
// ...
public profiles: Profiles;
Run Code Online (Sandbox Code Playgroud)

或者直接告诉 Typescriptthis.profilesstring[]类型:

public profiles: string[];
Run Code Online (Sandbox Code Playgroud)