Typescript error: Argument of type 'Object'

2020-04-27 13:33发布

问题:

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:

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?

EDIT

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

回答1:

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

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


回答2:

Your subscribe() function needs to pass any:

In your case (as already indicated in the comments):

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

In some cases it might be like this:

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