Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

399
Visualizações
TypeScript: Property 'name' does not exist on type 'any[]'

For some reason I can not run my React app, because following error:

TypeScript: Property 'name' does not exist on type 'any[]'.

I am exporting my TS type based on my API data:

export type CartItemType = {
  id: number;
  name: string;
  image: string;
  amount: number;
  chair: {
    name: string;
    colors: {
      white: {
        hex: string;
      };
    };
  };
};

Fetching the data:

  const getProducts = async (): Promise<CartItemType[]> =>
  await (await fetch("apiEndpoint")).json();

 const [cartItems, setCartItems] = useState([] as CartItemType[]);
 const { data, isLoading, error } = useQuery<CartItemType[]>(
    "products",
    getProducts
  );

I would like to select the fetched data and I am doing it in such a way:

const [selectedData, setSelectedData] = React.useState([]);

{data?.map((item) => (
            <button onClick={() => setSelectedData(item)}>SHOW</button>
{selectedData === item ? (
                <p>{selectedData.chair.description}</p>
 ) : null}

Unfortunately I am having this error on selectedData:

This condition will always return 'false' since the types 'any[]' and 'CartItemType' have no overlap.

I don't really know what that means and how to fix it. enter image description here

It would work only when I would specify the number in object array like this:

selectedData[0].name

But I have to make it work for selectedData.name

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You must aware of the value that the state is going to hold. It is important because the state update cause the re-render of the application.

Change your initial value of selectedData state variable to {}.

const [selectedData, setSelectedData] = React.useState({} as CartItemType);

Reason: Initially you are holding array value in a state and then later you are setting the state with objects and performed operation assuming it's an object. So, it's obvious that you must hold object value in the selectedData state.

This is the reason that you are getting this error message.

This condition will always return 'false' since the types 'any[]' and 'CartItemType' have no overlap.

The good part: I have made that change in the sandbox and the error goes away.

about 4 years ago · Juan Pablo Isaza Relatório

0

The accepted answer will fix the error but ideally you want to avoid Type casting

In my opinion, it is safer to set selectedData to null first to make sure you only use it if it has a correct value:

const [selectedData, setSelectedData] = React.useState<CartItemType | null>(null);

Then in your code you can do

if(selectedData) {
  ...
}

or

selectedData ? ... :
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda