Home > Net >  TypeScript issue array of objects
TypeScript issue array of objects

Time:01-26

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;

enter image description here

CodePudding user response:

You have to type your cities array, e.g. something like that (your props of Card may require actually different 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;

CodePudding user response:

You haven't defined the type of cities in Props.

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

for example:

type Props = {
  cities: CityType[];
};
  •  Tags:  
  • Related