user1222324562
user1222324562

Reputation: 1075

Convert Firestore value changes to Typescript object

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
});

Upvotes: 0

Views: 793

Answers (1)

user1222324562
user1222324562

Reputation: 1075

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 => {
        // ....
    });

Upvotes: 1

Related Questions