Angular: error TS2322: Type 'ItemsResponse'

2020-02-14 09:05发布

问题:

I am getting this error with my component not sure what to do?

here is the component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-emails',
  templateUrl: './emails.component.html',
  styleUrls: ['./emails.component.scss']
})

export class EmailsComponent implements OnInit {

test = 'test';
results: string[];

  constructor(private http: HttpClient) { }

  ngOnInit() {

    interface ItemsResponse {
      results: string[];
    }

    this.http.get<ItemsResponse>('assets/api/email_list.json').subscribe(data => {
      this.results = data;
      console.log(this.results);
    });
  }

}

and then I am getting this error, oddly enough, is working in the browser even with the error?

ERROR in src/app/components/emails/emails.component.ts(24,7): error TS2322: Type 'ItemsResponse' is not assignable to type 'string[]'.
src/app/components/emails/emails.component.ts(24,7): error TS2322: Type 'ItemsResponse' is not assignable to type 'string[]'.
  Property 'includes' is missing in type 'ItemsResponse'.

edit: added json snippet:

[
    {
        "pk": "wGR",
        "created": "2017-10-07T01:42:25.110747Z",
        "email_domain": "domain.com",
        "sender_name": null,
        "sender_email": "user@domain.com",
        "has_user_viewed": false,
        "is_shielded": false
    }
]

adding this so we know where we are at with this and for historical reasons so I learn something new here! current revision:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-emails',
  templateUrl: './emails.component.html',
  styleUrls: ['./emails.component.scss']
})

export class EmailsComponent implements OnInit {

results: ItemsResponse[]

  constructor(private http: HttpClient) { }

  ngOnInit() {

    interface ItemsResponse {
      pk: string;
      created: string;
      email_domain: string;
      sender_name: string;
      sender_email: string;
      has_user_viewed: boolean;
      is_shielded: boolean;
    }

    this.http.get<ItemsResponse>('assets/api/email_list.json').subscribe(data => {
      this.results = data.results;
      console.log(this.results);
    });
  }

}

回答1:

Edit

Now that we have the data structure:

[
    {
        "pk": "wGR",
        "created": "2017-10-07T01:42:25.110747Z",
        "email_domain": "domain.com",
        "sender_name": null,
        "sender_email": "user@domain.com",
        "has_user_viewed": false,
        "is_shielded": false
    }
]

you should probably create an interface like this:

interface ItemsResponse {
  pk: string;
  created: string;
  email_domain: string;
  sender_name: string;
  sender_email: string;
  has_user_viewed: boolean;
  is_shielded: boolean;
}

and change the definition of results to results: ItemsResponse[].

That means that this.results will be an array, each element being an ItemsResponse object.

After the request completes, you'll be able to access it as you would expect:

this.results[0]["sender_email"]
this.results[12]["pk"]
this.results.map(item => console.log(item.pk))

and so on.

Note that in my interface I have used just string for the pk field, but if you have a limited set of possible values, like "wGR", "wGA", "wGP" you can use a string enum type like so:

interface ItemsResponse {
  pk: "wGR" | "wGA" | "wGP";
  // ...
}

To explicitly explain why you had the error, however, you cannot cast an ItemsResponse to a string[], which is what you were doing by asserting the response of your get request as <ItemsResponse> (doing this tells the typechecker that data will be an ItemsResponse), but you then assign it to this.results, which you have declared as a string[]. Hopefully the illustration above shows why this won't work.

Original version

You have a type interface which defines a field called results:

interface ItemsResponse {
  results: string[];
}

In your service, you cast email_list.json to <ItemsResponse>:

this.http.get<ItemsResponse>('assets/api/email_list.json').subscribe(data => {
  this.results = data;
  console.log(this.results);
});

which means it expects email_list.json to look like this:

{
  "results": [
    "one@example.com",
    "two@example.com"
  ]
}

while it's likely actually

[
  "one@example.com",
  "two@example.com"
]

So you need to either

  1. assign it as this.results = data.results, or
  2. change the type interface to be simply string[]


回答2:

here: this.http.get<ItemsResponse> you are declaring that http.get's response data's type would be of ItemsResponse. and before that, inside your class you are declaring that results is an array of strings: results: string[];. but inside http's response, you are assigning the response to this.results. try this.results = data.results. but make sure that the type of the response is truly of type ItemsResponse. maybe use console.log