[英]Typescript error 'argument of type is not assignable to parameter of type'
[英]Typescript error: Argument of type 'Object' is not assignable to parameter of type '{}[]'
我正在使用Angular Material表组件,如下所示:
this.userService.getUsers().subscribe((response) => {
this.users = new MatTableDataSource(response);
});
它可以工作,但是在编译时会引发以下打字错误:
类型“ Object”的参数不能分配给类型“ {} []”的参数。 “对象”类型可分配给很少的其他类型。 您的意思是改用“ any”类型吗? 类型“对象”中缺少属性“包含”。
所以我尝试将其更改为:
this.users = new MatTableDataSource<any>(response);
但是还是一样的错误。 response
如下所示:
[{
userId: 123,
username: 'Tom'
}, {
userId: 456,
username: 'Joe'
}]
任何想法如何摆脱错误?
编辑
应该提到我是否这样做:
this.users = new MatTableDataSource([response]);
错误消失了,但是表格却无法正常工作,因为格式不是表格所期望的正确格式。 只是要注意这一点,以防它弄清楚可能是什么原因...
类型“ Object”的参数不能分配给类型“ {} []”的参数。
这并不意味着MatTableDataSource
接受错误的参数,而是您的response
具有错误的类型。 您应该明确地打字:
(response: {userId: number, username: string }[]) =>
或通过时执行以下操作:
new MatTableDataSource(response as {userId: number, username: string }[])
您的subscribe()
函数需要传递any
:
在您的情况下(如注释中已指出):
this.users = new MatTableDataSource(<any> response);
在某些情况下,可能是这样的:
const myLocalData = this.getData(<any> response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.