user11182249
user11182249

Reputation:

How to cast a snapshot value into a dictionary value with typescript?

How can I convert a snapshot value into a dictionary value of type [String: AnyObject]

I am trying to accomplish the bellow line in swift but in Typescript, so that I can loop through the keys. How can I do that? How do I cast a snapshot returned by firebase query in typescript into a dictionary of [string: AnyObject]

let snapValue = snap.value as! [String: AnyObject]

TypeScript query:

const userRef = admin.database().ref('PeopleWhoFollowMe').child(uid)
const fetchAndUpdate = userRef.once('value')
.then(snap => {

Upvotes: 4

Views: 1333

Answers (2)

Eric
Eric

Reputation: 1775

You can write your own converter as described in Firestore documentation.

firebase.firestore.FirestoreDataConverter<T> - Converter used by withConverter() to transform user objects of type T into Firestore data.

Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.

class Post {
  constructor(readonly title: string, readonly author: string) {}

  toString(): string {
    return this.title + ', by ' + this.author;
  }
}

const postConverter = {
  toFirestore(post: Post): firebase.firestore.DocumentData {
    return {title: post.title, author: post.author};
  },
  fromFirestore(
    snapshot: firebase.firestore.QueryDocumentSnapshot,
    options: firebase.firestore.SnapshotOptions
  ): Post {
    const data = snapshot.data(options)!;
    return new Post(data.title, data.author);
  }
};

const postSnap = await firebase.firestore()
  .collection('posts')
  .withConverter(postConverter)
  .doc().get();
const post = postSnap.data();
if (post !== undefined) {
  post.title; // string
  post.toString(); // Should be defined
  post.someNonExistentProperty; // TS error
}

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317392

The snap in your query is a DataSnapshot type object. Click through that link to read the API documentation for it.

You can get the raw JavaScript data object of a DataSnapshot using its val() method. Then you can iterate its properties using any normal JavaScript technique that's discussed heavily already on Stack Overflow: Iterate through object properties

Upvotes: 3

Related Questions