打字稿错误:“对象”类型的参数不能分配给“{} []”类型的参数 [英] Typescript error: Argument of type 'Object' is not assignable to parameter of type '{}[]'

查看:125
本文介绍了打字稿错误:“对象”类型的参数不能分配给“{} []”类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular Material表组件,如下所示:

I'm using the Angular Material table component like so:

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

它有效,但在编译时会抛出以下打字稿错误:

It works but when compiling it throws the following typescript error:


对象类型的参数不能分配给
'{} []'类型的参数。 对象类型可分配给极少数其他类型。
你的意思是使用'any'类型吗?属性'包含'在'对象'类型中缺少

Argument of type 'Object' is not assignable to parameter of type '{}[]'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'includes' is missing in type 'Object'.

所以我尝试将其更改为:

So I tried changing it to:

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

但仍然是同样的错误。 回复如下所示:

But still same error. response looks like this:

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

任何想法如何摆脱错误?

Any idea how to get rid of the error?

编辑

如果我这样做,请提及:

Should mention if I do this:

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

错误消失但表格不起作用,因为格式不正确这是表的预期。只是注意到这一点,以防它可能是什么原因...

the error goes away but then the table doesn't work because the format isn't the right one that's expected by the table. Just noting this in case it sheds any light as to what may be the cause...

推荐答案


'对象'类型的参数不能分配给'{} []'类型的参数。

Argument of type 'Object' is not assignable to parameter of type '{}[]'.

这并不意味着 MatTableDataSource 接受错误的参数,而是响应的类型错误。您应该明确指出:

That does not mean that MatTableDataSource accepts the wrong parameter, but rather that your response has the wrong type. You should definetly typecast that:

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

或在传递时执行此操作:

or do that when passing it:

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

这篇关于打字稿错误:“对象”类型的参数不能分配给“{} []”类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆