简体   繁体   中英

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.

I'm getting this from TypeScript

Property 'max_temp' does not exist on type 'never'.

Property 'min_temp' does not exist on type 'never'.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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