简体   繁体   English

TypeScript 发出对象数组

[英]TypeScript issue array of objects

What I'm trying to do is map an array which contains objects with properties and other nested objects to return a React component which I previously imported.我要做的是 map 一个数组,其中包含具有属性的对象和其他嵌套对象,以返回我之前导入的 React 组件。

I'm getting this from TypeScript我从 TypeScript 得到这个

Property 'max_temp' does not exist on type 'never'. “从不”类型上不存在属性“max_temp”。

Property 'min_temp' does not exist on type 'never'. “从不”类型上不存在属性“min_temp”。

My guess is that TypeScript complains because it doesn't know my array contains nested objects inside so it says I'm never going to get anything calling that.我的猜测是 TypeScript 抱怨是因为它不知道我的数组里面包含嵌套对象,所以它说我永远不会得到任何调用它的东西。 This is my code (down below I will post a screenshot)这是我的代码(下面我将发布截图)

import React from "react";
import Card from "./Card";
type Props = {
  cities: [];
};

const Cards: React.FC<Props> = ({ cities }) => {
  return (
    <div>
      {cities.map(({ name, main, weather }) => {
        return (
          <Card
            name={name}
            max={main.max_temp}
            min={main.min_temp}
            img={weather[0].icon}
            onClose={() => alert({ name })}
          />
        );
      })}
    </div>
  );
};
export default Cards;

在此处输入图像描述

You haven't defined the type of cities in Props.您尚未在 Props 中定义城市类型。

type Props = {
  cities: []; <--- what is this array of?
};

for example:例如:

type Props = {
  cities: CityType[];
};

You have to type your cities array, eg something like that, depending on your actual types:您必须输入您的城市数组,例如类似的东西,具体取决于您的实际类型:

import React from "react";
import Card from "./Card";
type Props = {
  cities: [
    { name: string, 
      main: {
         max_temp: number, 
         min_temp: number
      }, 
      weather: Array<{icon: any}> 
    }];
};

const Cards: React.FC<Props> = ({ cities }) => {
  return (
    <div>
      {cities.map(({ name, main, weather }) => {
        return (
          <Card
            name={name}
            max={main.max_temp}
            min={main.min_temp}
            img={weather[0].icon}
            onClose={() => alert({ name })}
          />
        );
      })}
    </div>
  );
};
export default Cards;

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

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