简体   繁体   English

如何定义和处理接口?

[英]How to define and deal with interface?

I have a interface for city details as follows: 我有一个有关城市详细信息的界面,如下所示:

export interface CityDetail {
    [index: number]: {
        id?: number,
        name: string,
        latitude?: string,
        longitude?: string,
        current_temperature?: string,
        current_humidity?: string,
        temp_max?: string,
        temp_min?: string,
        current_wind?: string,
        current_wind_pressure?: string,
        current_weather_condition?: string
    };
};

This interface I want to define as 我想定义为

 const countryClimate: CityDetail = {
                id: items['id'],
                name: items['name'],
                current_temperature: items['main']['temp'],
            };

But I am getting error 但是我得到了错误

Type '{ id: any; name: any; current_temperature: any; }' is not assignable to type 'CityDetail'.
  Object literal may only specify known properties, and 'id' does not exist in type 'CityDetail'.ts

Can anybody tell me what mistake I did? 谁能告诉我我犯了什么错误?

I think your items object like this 我认为您的物品是这样的

const items: Item = {
    id: any;
    name: any;
    current_temperature: any;
}

You should change item object type or do that: 您应该更改项目对象类型或执行以下操作:

 const countryClimate: CityDetail = {
     id: items['id'] as number,
     name: items['name'] as string,
     current_temperature: items['main']['temp'] as string,
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM