danseethaler
danseethaler

Reputation: 877

Define firebase data structure with TypeScript

I'm writing a React application using Firebase as the data store and I'm working on integrating TypeScript. I'm curious how to define the data structure used in Firebase so TypeScript will allow me to pull in the data.

The Firebase backend stores a list of acronyms with some information as defined in this interface

interface Acronym {
  id: string;
  short: string;
  full: string;
  description: string;
  category: string;
}

I have a component that fetches the Firebase data in the componentDidMount lifecycle method and then pushes the response into a stored state which is an array of Acronym type.

componentDidMount() {
  db
    .collection('acronyms')
    .onSnapshot(querySnapshot => {
      const acronyms: Acronym[] = [];

      querySnapshot.forEach(doc => {
        acronyms.push(doc.data());
      });

      this.props.updateState({acronyms});
    });
}

TypeScript throws an error on acronyms.push(doc.data()); since the doc.data() does not have a defined return type of Acronym. How can I tell TypeScript that the doc.data() will return the Acronym type?

Upvotes: 1

Views: 1344

Answers (1)

Leonardo Gabriel
Leonardo Gabriel

Reputation: 347

It may be happening, as the error says, doc.data() does not have a defined return type of Acronym. May be the doc.data() has another attribute, and you don't have it in your Acronym's interface.

You could try something like this:

querySnapshot.forEach(doc => {
  acronyms.push({id: doc.data().id, short: doc.data().short, full: doc.data().full, description: doc.data().description, category: doc.data().category});
});

In this way, you would be inserting an object exactly with the same attributes of its interface.

I hope it really helps you!!

Upvotes: 1

Related Questions