2

As you can see in the code snippet below, a certain React element should be shown according to a variable of value type boolean. However, even when checking if the selectedRepository is truthy and coercing it to a Boolean, the TS compiler gives the error Object is possibly 'null'

{...}
  const shouldShowRepositoryDetails = !isLoading && Boolean(selectedRepository);

  return (
    <Layout header={<RepositoryDetailsHeader />}>
      {shouldShowRepositoryDetails && (
        <RepositoryDetailsContainer>
          <header>
            <img
              src={selectedRepository.owner?.avatar_url}
              alt={selectedRepository.owner?.login}
              aria-label={selectedRepository.owner?.login}
              title={selectedRepository.owner?.login}
            />

            <div>
              <strong>{selectedRepository.full_name}</strong>
              <p>{selectedRepository.description}</p>
            </div>
          </header>
        </RepositoryDetailsContainer>
      )}
    </Layout>
  );

Error Description

I would like to understand if this is a TS issue or if someone already experienced this.

6
  • 1
    Don't put images of your code, paste your code as text with the proper formating. Commented Jan 8, 2021 at 14:10
  • Sure! My apologies. I understand that adding directly the code snippet helps in order to test it. Commented Jan 8, 2021 at 14:12
  • Why null or false would be coerced to 0 when printed into the HTML? May you send me a resource or an example of this issue? Also, I've tried with ternary operators and the issue persists. Commented Jan 8, 2021 at 14:16
  • Coercion to boolean is not sufficient. You need a user defined type guard. It isn't enough for it to be truthy, the compiler has to know that it is a type that has the properties you're accessing. Commented Jan 8, 2021 at 14:17
  • 1
    @JaredSmith I didn't know about type guards and I'm reading about it now. I've defined a utility function to check the selectedRepository, using the following type guard selectedRepository is Repository, and now it works 🎉 Commented Jan 8, 2021 at 14:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.