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

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

问题描述

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

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:

'Object' 类型的参数不可分配给类型的参数'{}[]'.对象"类型可分配给很少的其他类型.做过你的意思是使用'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);

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

But still same error. response looks like this:

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

知道如何消除错误吗?

编辑

应该提及我是否这样做:

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...

推荐答案

Object"类型的参数不可分配给{}[]"类型的参数.

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

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

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 }[])

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

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