typescript 如何在对象数组中声明接口?

gopyfrb3  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(178)

我在这里尝试的是在我的变量中用对象数组声明一个接口。在这种情况下如何声明接口?如果我把变量声明为any,它就能正常工作。

export interface mWeather
{
    date: Date;
    temperatureC: number;
    tempartureF: number;
    summary: string;
}

weatherinfo: mWeather [] = [];
//weatherinfo: any = {}; This line works fine.

getWeatherInfo(){
   this.http.get(url).subscribe(response:(how can I declare type here too)=> 
   
   this.weatherinfo = response);
}

如果我声明weatherinfo:{};然后它工作正常。
我的数据:

[
    {
        "date": "2023-05-20",
        "temperatureC": 54,
        "temperatureF": 129,
        "summary": "Hot"
    },
    {
        "date": "2023-05-21",
        "temperatureC": 34,
        "temperatureF": 93,
        "summary": "Scorching"
    },
    {
        "date": "2023-05-22",
        "temperatureC": 8,
        "temperatureF": 46,
        "summary": "Chilly"
    },
    {
        "date": "2023-05-23",
        "temperatureC": -19,
        "temperatureF": -2,
        "summary": "Hot"
    },
    {
        "date": "2023-05-24",
        "temperatureC": 34,
        "temperatureF": 93,
        "summary": "Bracing"
    }
]
ffscu2ro

ffscu2ro1#

使用HttpClient.get()方法#Overload 15.你的代码应该如下:

getWeatherInfo(){
  this.http.get<mWeather[]>(url).subscribe((response: mWeather[])=> {
   
     this.weatherinfo = response;
  });
}

相关问题