Angular: error TS2322: Type 'ItemsResponse' is not assignable to type 'string[]'

前端 未结 2 1252
礼貌的吻别
礼貌的吻别 2020-12-21 06:26

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

here is the component:

import { Component, OnInit } from \'@angular/core\';
import { H         


        
2条回答
  •  醉酒成梦
    2020-12-21 06:58

    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 (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 :

    this.http.get('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[]

提交回复
热议问题