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

135
Visualizações
Typescript and react - Object is possibly 'null'

So I have object in typescript used in react components that has this type:

export type DataInfoTypes<dataType> = {
  data: dataType | null;
  loading: boolean;
  error: boolean;
};

Let's assume that "dataType" there would be (should not matter, just an object of strings):

{[key in string]: string}

Then when I use this data in React component, I check if object.data is not null:

if (!materials.data || materials.loading) {
  return <DataLoading />;
}

Then in my return function, when I reference data it seems okay:

<Flex alignItems="center" direction="column">
  <Text>{materials.data["somekey"]}</Text>
  <VStack w="100%" ....

However few lines down I have an array map method(in same component, same return):

<VStack w="100%" align="center">
  {sources.map((matKey: string, index: number) => {
    return <Text key={index}>{materials.data["somekey"]}</Text>
  }
</VStack>

And I get this error:

Object is possibly 'null'. TS2531

Any ideas on how to fix this or what is the cause? (Please exclude all the tsignore solutions if possible)
Big thanks to everyone responding.

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

0

The declared type of data is dataType or null. What the ts compiler is telling you is that you are trying to access a property (.someKey) of a possibly null value, which will result into a runtime error.

To fix it, use optional chaining:

materials.data?.somekey

which will return the value of data.somekey when data is not null and undefined when data is null.

Most importantly, optional chaining does not throw a runtime error when data is falsy.

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