How to deal with objects waiting for fetch in Typescript

Tags: , ,

I’m moving from javascript to typescript, and this is an error that I encounter multiple times:

In a component, I’m awaiting a fetch to return an object, and until that time, the component returns null. If the object is there, I will render some properties of the object:

const Component = () => {
  const [user, setUser] = useState(null)

  useEffect(() => {
  }, [getUser])

  if (!user) return null

  return (
      <li>{`Username: ${user.userName}`}</li>
      <li>{`Email: ${}`}</li>

Typescript then throws an error Object is possibly 'null'. TS2531

For a more general case, this question already has an answer here: How to suppress “error TS2533: Object is possibly ‘null’ or ‘undefined'”?

However, assuring that the object is never null doesn’t feel right. I mean, I could initialise the object;

const [user, setUser] = useState({ userName: 'UNKNOWN', email: 'UNKNOWN' })

but that clearly doesn’t seem to be the best solution to me either.

I’m disappointed that typescript doesn’t recognise that the user can never be null when it reaches the JSX. But this is probably because I’m thinking way to naively about this.

Remains the question – how do I deal with this typical scenario in a typescript component?


Issue here is that you don’t tell to TypeScript, what type can have the user state. To fix it, just define a type for User and specify in the useState:

type User = {
  userName: string;
  email: string;

const [user, setUser] = React.useState<User | null>(null);

Edit friendly-mountain-g9m5x

Source: stackoverflow