0

I have the interfaces:

interface Item {
    data: string
}

interface Test {
    item: Item
    url: string
}

My data in Firestore is stored as follows

Collection Tests
    id: {
        item: {
            data: "some data"
        },
        url: "abc.com",
    }
}

How can I type the incoming objects on a collection read?

this.db.collection('tests').valueChanges().subscribe(tests => {
    // Do some sort of type conversion
});

Or better yet could I do something like this:

this.db.collection('tests').valueChanges().subscribe<Test[]>(tests => {
    tests[0].url // valid typescript
});
2
  • So, to be clear, are you saying that your document contains an object type field named item which has a string property called data? Commented Aug 13, 2019 at 20:30
  • The documents field item is a Firestore Map with a key data Commented Aug 13, 2019 at 20:35

1 Answer 1

1

Updated

According to this the simplest way to achieve a typed result is by adding the type after collection

this.db.collection<Test>('tests').valueChanges().subscribe(tests => {
    // ....
});

Old Answer

This is the only solution I have come up with, but I am looking for something more readable

    this.db.collection('tests').valueChanges().pipe(
        map(tests => {
            return tests as Test[];
        })
    ).subscribe(fs_tests => {
        // ....
    });
Sign up to request clarification or add additional context in comments.

1 Comment

If you just want a straight cast (assuming that the document always exactly matches your interfaces), it's not going to get any simpler than this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.