【问题标题】:Typescript error: Argument of type 'Object' is not assignable to parameter of type '{}[]'打字稿错误:“对象”类型的参数不可分配给“{} []”类型的参数
【发布时间】:2018-06-13 14:04:48
【问题描述】:

我像这样使用Angular Material table component

    this.userService.getUsers().subscribe((response) => {
        this.users = new MatTableDataSource(response);
    });

它可以工作,但是在编译时会抛出以下打字错误:

“对象”类型的参数不能分配给类型参数 '{}[]'。 “对象”类型可分配给极少数其他类型。做过 您的意思是改用“任何”类型?缺少属性“包含” 在类型“对象”中。

所以我尝试将其更改为:

this.users = new MatTableDataSource<any>(response);

但还是同样的错误。 response 看起来像这样:

[{
    userId: 123,
    username: 'Tom'
}, {
    userId: 456,
    username: 'Joe'
}]

知道如何摆脱错误吗?

编辑

如果我这样做,应该提及:

this.users = new MatTableDataSource([response]);

错误消失了,但表格无法正常工作,因为格式不是表格所期望的正确格式。只是注意到这一点,以防它揭示可能是什么原因......

【问题讨论】:

  • 你尝试过类型转换吗?例如。 response as any
  • 您需要更改subscribe() 函数以将正确的(数组)类型传递给其回调参数。
  • @JonasW。是的!这工作this.users = new MatTableDataSource(&lt;any&gt; response);谢谢

标签: javascript angular typescript


【解决方案1】:

你的subscribe()函数需要通过any

在你的情况下(如 cmets 所示):

this.users = new MatTableDataSource(<any> response);

在某些情况下可能是这样的:

const myLocalData = this.getData(<any> response);

【讨论】:

    【解决方案2】:

    “Object”类型的参数不能分配给“{}[]”类型的参数。

    这并不意味着MatTableDataSource 接受了错误的参数,而是您的response 具有错误的类型。您应该明确地进行类型转换:

      (response: {userId: number, username: string }[]) =>
    

    或在传递时这样做:

     new MatTableDataSource(response as {userId: number, username: string }[])
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2018-06-19
      • 1970-01-01
      • 2017-08-12
      • 2016-09-26
      • 2018-05-25
      • 1970-01-01
      • 2021-10-18
      • 2021-03-02
      相关资源
      最近更新 更多