[英]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.