What is the best way to assign an index signature to a plain object?

Currently, I have this object:

const events = {
  i: 'insert',
  u: 'update',
  d: 'delete'
};

I am struggling to assign an index signature to the object. When I try the following:

export interface EventsSignature {
  [key:string]: string
}

const events = <EventsSignature>{
  i: 'insert',
  u: 'update',
  d: 'delete'
};

it doesn't seem to work as it simply overrides the initial object definition. The same issue arises when I attempt something similar with another code snippet:

export class OplogObservable {

  private uri: string;
  private coll: Collection;
  collName: string;
  isTailing = false;

  private subs = {
    all: new Subject<any>(),
    update: new Subject<Object>(),
    insert: new Subject<Object>(),
    delete: new Subject<Object>(),
    errors: new Subject<Object>(),
    end: new Subject<Object>()
  };

}

If I use new OplogObservable().subs[type], it throws an error mentioning the absence of an index signature.

Answer №1

The index signature of the object literal is already present, but it restricts indexing to keys that are part of the type:

export class OplogObservable {

    private subs = {
        all: new Subject<any>(),
        update: new Subject<Object>(),
        insert: new Subject<Object>(),
        delete: new Subject<Object>(),
        errors: new Subject<Object>(),
        end: new Subject<Object>()
    };
    test(type: string) {
        this.subs['all'] // accessing with a constant is allowed
        let subs = this.subs;
        this.subs[type as keyof typeof subs] // type assertion on the key allows access
    }
}

If you want to index using any arbitrary string, you can use a type assertion to 'any':

 (this.subs as any)[type]

Alternatively, you can create a helper function to generate an object with both properties and an indexer:

function eventsHelper<T extends { [name: string] :Subject<any> }>(subs: T) : T & { [name: string] :Subject<any> }{
    return subs;
}
export class OplogObservable {

    private subs = eventsHelper({
        all: new Subject<any>(),
        update: new Subject<Object>(),
        insert: new Subject<Object>(),
        delete: new Subject<Object>(),
        errors: new Subject<Object>(),
        end: new Subject<Object>()
    });
    test(type: string) {
        this.subs.all // properties are preserved
        this.subs[type] // simple string indexing is allowed
    }
}

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

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...

Encountering an issue in Angular where data.slice is not functioning properly, resorting to using parseInt to convert strings into Date

Looking to convert the data retrieved from the database into numbers and dates with ease. One set of data is in milliseconds while the other is in timestamps. https://i.stack.imgur.com/HdM0D.png The goal is to transform both types into numbers first, the ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Is Angular 9's default support for optional chaining in Internet Explorer possible without the need for polyfill (core-js) modifications with Typescript 3.8.3?

We are in the process of upgrading our system to angular 9.1.1, which now includes Typescript 3.8.3. The @angular-devkit/[email protected] utilizing [email protected]. We are interested in implementing the optional chaining feature in Typescript ...

Tips on configuring a segment in an Angular 6 route

Question: I am looking to configure a specific segment after the user logs in, for example http://localhost:4200/#/{dynamic name}/{dynamic name}/app/... However, I am facing an issue when navigating to /app/... across the application. Is there a way to a ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

Guide to configure Validator to reject the selection of the first index option in Angular 2

When using a select option, it should be set up like: <div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success&ap ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Transfer the data stored in the ts variable to a JavaScript file

Is it possible to utilize the content of a ts variable in a js file? I find myself at a loss realizing I am unsure of how to achieve this. Please provide any simple implementation suggestions if available. In my ts file, there is a printedOption that I w ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

Why is the dateclick event in PrimeNG's FullCalendar not being emitted when clicking on a date? What is the best way to handle click events on specific dates within the calendar?

I am new to using Angular and PrimeNG, and I am facing challenges while trying to implement the FullCalendar component. The specific component I am referring to can be found here: The issue arises when I attempt to trigger an event when a user clicks on a ...

Recursively map elements of a TypeScript array to keys of an object

I am looking to create a structured way to specify paths for accessing objects, ensuring that the path is correctly typed based on the object type. Let me illustrate with an example. Consider the following data: const obj = { name: 'Test', ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Declaration of dependencies for NestJS must include dependencies of dependencies

I'm encountering an issue where NestJS is not automatically resolving dependencies-of-dependencies: I have created an AWSModule which is a simple link to Amazon AWS with only a dependency on the ConfigService: @Module({ imports: [ConfigModule], ...