角度:错误TS2322:类型'ItemsResponse'无法分配给类型'字符串[]' [英] Angular: error TS2322: Type 'ItemsResponse' is not assignable to type 'string[]'

查看:172
本文介绍了角度:错误TS2322:类型'ItemsResponse'无法分配给类型'字符串[]'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件出现此错误,不确定该怎么办?

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

这是组件:

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

添加了json片段:

[
    {
        "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);
    });
  }

}

推荐答案

编辑

现在我们有了数据结构:

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;
}

,然后将results的定义更改为results: ItemsResponse[].

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

这意味着this.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))

以此类推.

请注意,在我的界面中,我仅对pk字段使用了string,但是如果您可能的值集有限,例如"wGR", "wGA", "wGP",则可以使用如下的字符串枚举类型:

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";
  // ...
}

要明确说明为什么会出现错误,您不能将ItemsResponse强制转换为string[],这就是通过将get请求的响应声明为<ItemsResponse>来执行的操作(这样做可以告诉类型检查器(data将是ItemsResponse),但是随后将其分配给了声明为string[]的this.results.希望上面的插图能说明为什么它不起作用.

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.

您有一个类型接口,该接口定义了一个名为results field :

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

interface ItemsResponse {
  results: string[];
}

在您的服务中,您将email_list.json强制转换为<ItemsResponse>:

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);
});

这意味着它希望email_list.json看起来像这样:

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

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

虽然可能实际上是

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

所以你要么

  1. 将其分配为this.results = data.results,或
  2. 将类型界面更改为string[]
  1. assign it as this.results = data.results, or
  2. change the type interface to be simply string[]

这篇关于角度:错误TS2322:类型'ItemsResponse'无法分配给类型'字符串[]'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆