Property not exsisting on a type in React with TypeScript

Here I am getting the error: Property ‘uid’ does not exist on type ‘User | null’. and Property ‘photoURL’ does not exist on type ‘User | null’. Now I get that I have to define an interface and do this.

You are thinking that you need to define an interface because your component doesn’t know the type of auth.currentUser. But that is not how that error message reads to me. Typescript believes that the type of auth.currentUser is User | null. So there is already a User type or interface, which presumably has a whole bunch of properties and probably already defines uid and photoURL. That’s not the issue. The issue is the | null part. auth.currentUser is either a User object representing the current user, or it’s null. You can’t destructure it until you know that it’s an object and not null. That is what the error is saying.

So we need to check the value and make sure that we don’t have null:

const sendMessage = async (e: any) => {
  e.preventDefault();

  const user = auth.currentUser;

  if (user) {
    const { uid, photoURL } = user;

    await messagesRef.add({
      text: formValue,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      uid,
      photoURL,
    });

    setFormValue('');
    
  } else {
    // can handle error somehow
  }
};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top