Here is a snippet of code from my TypeScript project:
admin.firestore().collection('posts').doc(postId).get().then((data) => {
let likesCount = data.data()?.likesCount || 0;
let likes = data.data()?.likes || [];
let updateData = {};
if (action == 'like') {
updateData['likesCount'] = ++likesCount;
updateData[`likes.${userId}`] = true;
} else {
updateData['likesCount'] = --likesCount;
updateData[`likes.${userId}`] = false;
}
admin.firestore().collection('posts').doc(postId).update(updateData).then(() => {
response.status(200).send('Done');
}).catch((err) => {
response.status(err.code).send(err.message);
});
}).catch((err) => {
response.status(err.code).send(err.message);
});
I encountered an error while assigning values within the if & else blocks in this code that I copied from a tutorial.
The specific error messages are as follows:
Element implicitly has an 'any' type because expression of type '"likesCount"' can't be used to index type '{}'. Property 'likesCount' does not exist on type '{}'.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.
I attempted to create an interface and use it like so:
interface UpdateData {
likesCount: number,
likes: string
}
let updateData = {} as UpdateData;
However, this approach resulted in another error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'UpdateData'. No index signature with a parameter of type 'string' was found on type 'UpdateData'.
In addition, using this interface may not cover all the values associated with the data retrieved from Firestore. I want to ensure that these values still exist after updating the mentioned two fields.
If anyone could provide guidance on how to resolve this issue, I would greatly appreciate it.