'Typescript null checking custom hook return data when component not rendered

We are pulling in data and consuming it with Redux Tool Kit. We then conditionally render components based on the availability of that data. However if I use the custom RTK hook to access the data in the component that will not render without that data, Typescript still complains that the data is possibly null.

Parent

<Route path={"/cards"}>
  {person && <Cards />}
</Route>

Component

import { usePerson } from "store/hooks/person"

export const Cards = (): JSX.Element => {
  const { person } = usePerson()
  const { randomData } = useCards({person}) // person is possibly null here

We don't want to wrap null checks around everything. And ideally we should be able to use the RTK hooks to consume data rather the passing through component props. Or is this a bad approach?



Solution 1:[1]

Typescript is not able to check for null data across components because type checking would have to be done at runtime instead of compile time. The safest way to implement this would be to pass person in as a prop.

Parent

<Route path={"/cards"}>
  {person && <Cards person={person} />}
</Route>

Component

import { usePerson } from "store/hooks/person"

export const Cards = ({ person }: { person: PersonType }): JSX.Element => {
  const { randomData } = useCards({person})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ScarpMetal