【问题标题】:Angular: The 'Object' type is assignable to very few other types [duplicate]Angular:“对象”类型可分配给极少数其他类型[重复]
【发布时间】:2019-09-30 13:35:29
【问题描述】:

我的这段代码在 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 中的正确语法是什么?

【问题讨论】:

  • getProfiles() 的返回类型是什么。
  • 不要使用Object 来断言类型(参见docs)。
  • 你确定代码在抱怨这段代码吗?该消息说您将类型 Object 分配给了某个属性,这是非常通用的,您必须在这种情况下使用 any。

标签: angular


【解决方案1】:

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

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

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

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

例如;

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

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

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

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

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

  • 函数没有声明返回类型,必须推断它
  • http.get() 的返回类型是 Observable&lt;Response&gt; 类型,而不是 JSON 类型

我收到了这个错误:

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

这里有两种方法:

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

不管怎样,我认为你的升级还没有完成。

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

【讨论】:

  • ejem,真的不反序列化数据。这可以帮助您编写代码,但不多(也不少),简单地使用 .subscribe((profiles:any[])=&gt;{..}) 说 Angular 是一个数组
【解决方案2】:

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

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

// OR

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

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

export type Profiles = string[];
// ...
public profiles: Profiles;

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

public profiles: string[];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2021-05-21
    相关资源
    最近更新 更多