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

343
Visualizações
Why is the object possibly undefined in typescript, when an explicit undefined check is added via function?

Below is a small example, where I would like to ask, why the eslinter for typescript is complaining about the object, that it could be possibly undefined in that case, where an undefined-check is actually added, just that it is extracted into a separate function, so that is gets a more meaningful name.

import { ReactElement } from "react";
import "./styles.css";

interface Item {
  id?: string;
  images?: string[];
}

const itemHasImages = (item: Item): boolean =>
  item.images !== undefined && item.images.length > 0;

const renderItem = (item: Item): ReactElement => {
  if(itemHasImages(item)){ // <<< using this the compiler complains below in JSX that item could possibly be null
    // vs if(item.images !== undefined && item.images.length > 0) <<< here the compiler recognizes the check
    return (
      <>
        <img src={item.images[0]} alt={""} />
      </>
    );
  } else {
    return <></>
  }
};

export default function App() {
  const dummyItems = [
    {
      images: ["https://picsum.photos/200/300", "https://picsum.photos/200/300"]
    },
    {
      images: ["https://picsum.photos/200/300", "https://picsum.photos/200/300"]
    }
  ];

  if (itemHasImages(dummyItems[0])) {
    console.log("hello")
    renderItem(dummyItems[0]);
  } else {
    return <div>Hello</div>;
  }
  return <div>Hello</div>;
}

Please apologize weak formatting, for better interaction you can find a code-sandbox link here:

https://codesandbox.io/s/unruffled-bogdan-c74u6?file=/src/App.tsx

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Why the eslinter for typescript is complaining about the object, that it could be possibly undefined?

The reason is because you added a ? (optional) to the property in the interface declaration.

One way to fix it is to check for undefined when rendering it with the ? operator.

<img src={item.images ? item.images[0] : ""} alt={""} />

Note that is only hiding the issue, the real solution is to make sure you don't render that element if there're no images, i.e. add a !!item.images?.length check.

over 4 years ago · Santiago Trujillo Relatório

0

Unfortunately TypeScript does not understand what your function itemHasImages exactly does, even if it has the exact same body as an expression that TS may understand when it is inlined.

Therefore when you factorize your check in an external function, TypeScript can no longer use it to perform type narrowing (here to make sure that an optional property is actually present).

This is one of the cases where TypeScript may force us not to be "too smart" and leave an inline check.

Another acceptable solution is to force / cast the type after your check:

  if(itemHasImages(item)){
    const images = item.images as unknown as string[]; // Force type since we have externally verified it
    return (
      <>
        <img src={images[0]} alt={""} />
      </>
    );
  }

A more complex solution might be possible, by providing overload definitions for your itemHasImages function, so that TS can use them to perform type narrowing.

over 4 years ago · Santiago Trujillo 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