Is it feasible to have dynamic map members in `UpdateData` using Firestore Admin SDK?

There are different scenarios in which interfaces can be implemented:


interface MyInterface {
  // viewCount: { [userId: string]: number };
  downloaded?: { [userId: string]: boolean };
}
export type MyInterfaceUpdate = admin.firestore.UpdateData<MyInterface>;

export function a() {
  let a = "asdf"
  const update: MyInterfaceUpdate = {
    [`downloaded.${a}`]: true,
    // ['viewCount.testUser']: 23,
  }
}

Keep in mind that there should only be one map in the interface.

Alternatively, another implementation could look like this:

interface MyInterface {
  viewCount: { [userId: string]: number };
  downloaded?: { [userId: string]: boolean };
}
export type MyInterfaceUpdate = admin.firestore.UpdateData<MyInterface>;

export function a() {
  const update: MyInterfaceUpdate = {
    [`downloaded.asdf`]: true,
    ['viewCount.testUser']: 23,
  }
}

It seems that combining both implementations may lead to an error. Why is that so?

Take a look at the combined approach:

interface MyInterface {
  viewCount: { [userId: string]: number };
  downloaded?: { [userId: string]: boolean };
}
export type MyInterfaceUpdate = admin.firestore.UpdateData<MyInterface>;

export function a() {
  let a = "asdf"
  const update: MyInterfaceUpdate = { // Error here "index sigbatures are incompatible"
    [`downloaded.${a}`]: true,
    ['viewCount.testUser']: 23,
  }
}

Remember, it will work if downloaded and viewCount have the same types (both string or boolean).

Is there a way to make these combinations work harmoniously? :)

Answer №1

TypeScript doesn't comprehend the syntax you're attempting to use.

The data needed for your interface should be structured as follows:

const data: MyInterface = {
    viewCount: { "uid": 23 },
    downloaded: { "uid": true },
}

Attempting to emulate this using Firestore dot notation or any other form of string interpolation will not work. The update object for a Firestore document that modifies only those two fields will never align with the current definition of your interface - they have fundamentally different structures (specifically, just string keys mapped to values, regardless of how the string key is constructed).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The memory heap error in JavaScript arises during the Webpack build process

My Webpack configuration for a NodeJS project with TypeScript is causing a "JavaScript memory Heap" error during compilation. While I can increase the memory limit locally to generate the output build folder, the server has restrictions on memory usage. I ...

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...

Designing a versatile Angular component for inputting data (Mailing Address)

Currently, I am in the process of developing an Angular 11 application that requires input for three distinct mailing addresses. Initially, I thought I had a clear understanding of what needed to be done, only to encounter warnings about elements with non- ...

Create a function that accepts a class as a parameter and outputs an object of that class

I am working on an instantiator function that generates an instance of a provided class: declare type ClassType = { new (): any }; // known as "ParameterlessConstructor" function createInstance(constructor: ClassType): any { return new constructor(); ...

Creating instances of a child class in Typescript using a static method in the parent class, passing arguments and accessing other static methods

Struggling with instantiating a child class from a static method in a base class. Looking to properly specify the return type instead of resorting to using any for all static methods. Tried a solution here, but it falls short when dealing with static metho ...

Defining a JSON file interface in Angular to populate a dropdown box with dependencies

I've embarked on an exciting project to develop a cascading dropdown box filter, and it's proving to be quite challenging. I'm taking it step by step to ensure clarity. I have obtained a JSON file containing the data required to populate de ...

Tips on providing form validation in Ionic

I'm currently working on a registration form and I need some advice on how to implement custom name and email validation. Here is the structure of my form: registrationForm = this.formBuilder.group({ name: [''], email: ['' ...

Using functions as observer callbacks is not permitted in TypeScript

Here is a snippet of functional TypeScript code along with its test: menu.service.ts: import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; export class MenuService { private events = new Subject ...

How to create an empty @POST() body in NestJS for HTTPS requests

I am currently utilizing NestJS with HTTPS for my project. import { NestFactory } from '@nestjs/core'; import { fstat } from 'fs'; import { AppModule } from './app.module'; {readFileSync} from 'fs' async function boo ...

Leveraging thousands of on() event listeners in Firebase demonstrates exceptional design

We are looking to perform operations on our Firebase database and modify data based on user input from their mobile devices by changing a flag. Currently, we are using the `on()` method to listen to specific flags within each user's node. This listen ...

Ways to overlook compilation errors in Typescript/Electron for unreached code

I am diving into Typescript/Electron and attempting to create a text-based game. My journey began with a basic Electron application and I started implementing core logic using classes/interfaces that reference classes I have yet to implement. The snippet o ...

A guide on implementing TypeScript generics constraints when using the useState hook

Currently, I am delving into Typescript and have developed a custom React hook that resembles the following structure: import { useEffect, useState } from 'react'; type TypeOne = { one: string; }; type TypeTwo = { two: number; }; type TypeTh ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

How can we implement type guarding for a generic class in TypeScript?

Implementing a generic class in TypeScript that can return different types based on its constructor parameter. type Type = 'foo' | 'bar'; interface Res { 'foo': {foo: number}; 'bar': {bar: string}; } class ...

Why is the "typeof" function important in TypeScript member typings?

The definitions in the Electron typescript include an interface named MainInterface. This interface includes familiar members like app and autoUpdater, as well as less familiar ones such as BrowserView, BrowserWindow, and ClientRequest. One specific quest ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Utilizing a tuple for indexing in Typescript

Imagine you have a tuple containing keys like ["a", "b", "c"] and a nested object with these keys as properties {a: {b: {c: number}}}. How can you recursively access the members of the tuple as indices in typescript? An example implementation without prop ...

Vercel seems to be having trouble detecting TypeScript or the "@types/react" package when deploying a Next.js project

Suddenly, my deployment of Next.js to Vercel has hit a snag after the latest update and is now giving me trouble for not having @types/react AND typescript installed. Seems like you're attempting to utilize TypeScript but are missing essential package ...

The ability to reach a variable beyond its block

As a newcomer to TypeScript (coming from the Java world), I am experimenting with creating a mapper function like this: public getApercuTypePrestationFromTypePrestationEX044(typePrestationEX044: TypePrestationEX044): ApercuTypePrestation { let ape ...

Customizing the standard ping protocol for native JavaScript websockets

In my Expo (React Native) project, I am working on implementing a protocol to manage stale websocket connections on both the client and server sides. The 'ws' package offers built-in callback handling for the 'pong' event (and sending p ...