1

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.

2
  • what object is possibly null? materials.data["somekey"]? Commented Oct 12, 2021 at 18:57
  • just materials.data Commented Oct 12, 2021 at 20:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I understand what you are saying, but I have a condition before the return statement, that does check if materials.data is not null, so therefore it should be just "dataType" inside the return statement. It also shows no problem when it is inside top-level JSX tags, but when I use materials.data inside array.map function , then the problem occurs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.