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

Is it possible to run NestJS commands without relying on npx?

I recently installed nestjs using npm, but I encountered an issue where it would not work unless I added npx before every nest command. For example: npx nest -v Without using npx, the commands would not execute properly. In addition, I also faced errors ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Prevent the function from affecting type deduction

I am working with a type similar to this: interface Test<R, T> { inputType: R; transformer: (input: R extends any ? R : never) => T; } // function for inferring type function inferTest<T extends Test<any, any>>(t: T): T { ...

The outcome of a promise is an undefined value

I am facing an issue where I need to access the result of my API call outside the promise, but the value I receive is always undefined. Within the OrderService : public async getOrderPrice(device: string) : Promise<any> { this.urlOrderPrice = th ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...

Trouble setting custom attribute tags in Ionic 4

Trying to apply custom attributes within a ngFor loop is proving challenging for me. <ng-container *ngFor="let a of this.current_items?.areas; let i = index"> ... I've made several attempts: <div class="productBatchArea" custom-data=&apo ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

Transforming the window property in distinct entry points for TypeScript

During the initial page load, I am looking to transfer data from a template to a TypeScript file by attaching it to the window object. I want each page to utilize the same variable name for its specific data (window.data). An example of this can be seen in ...

Dealing with mistakes in an Angular service

I've been grappling with error handling in Angular. I attempted to handle errors within a service, but I'm uncertain if that's the correct approach. @Injectable({ providedIn: 'root', }) export class CaseListService { public con ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Error Message: Module not found while using Node Express with TypeScriptIssue: A

I have set up a straightforward node express app using TypeScript. My goal is to implement an errorMiddleware in the index.ts file. As I try to start the server, I encounter the following error: at Module.require (node:internal/modules/cjs/loader:100 ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

Top-notch approach for consolidating Typescript Declaration files into a single comprehensive file

Is there any efficient way to package declaration files together without using the module declaration approach? declare module "path/to/file" { ... } declare module "path/to/file/sub/file" { ... } and so on. I have encountere ...

Troubleshooting issues with accessing the _id property using Typescript in an Angular application

Encountering an Angular error that states: src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is ...

Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you. Error 1: There is an issue with converting type '({ Id: string ...

The isMobile variable from useSettings is failing to update correctly when the window is resized in a Next

I’ve encountered an issue with determining the device type (mobile, tablet, or desktop) in my Next.js application. I’ve utilized the is-mobile npm package to identify the device type and passing this data through settings. However, the isMobile flag fa ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...