Unable to set a value to a TypeScript object mapping

I encountered an issue with my typescript dictionary. Whenever I try to assign a value to it, a specific error occurs.

         TypeError: Cannot set property 'v1/items/someItemType/someItemId/EVENT/some
    DataTypeId' of undefined
          at MainClass.subscribe (G:\Projects\src\main\MainClass
    .js:9:3522)
          at Context.<anonymous> (G:\Projects\test\main\Wish.
    spec.js:45:18)
          at callFn (G:\Projects\node_modules\mocha\lib\runna
    ble.js:315:21)
          at Hook.Runnable.run (G:\Projects\node_modules\moch
    a\lib\runnable.js:308:7)
          at next (G:\Projects\node_modules\mocha\lib\runner.
    js:298:10)
          at Immediate._onImmediate (G:\Projects\node_modules
    \mocha\lib\runner.js:320:5)

This is the structure of my dictionary:

interface StringTopicToMyTopicMap {
  [topic: string]: MyTopic;
};

The interface for MyTopic is as follows:

export interface MyTopic {
  dataTypeID: string;
  itemID: string;
  itemType: string;
  dataType: MyDataType;
  qos: number;
}

Here is how I attempted to assign a value to the dictionary:

private subscriptionTopicsMap: StringTopicToMyTopicMap;

subscribe(myTopic: MyTopic) {
    if (_.isEmpty(myTopic)) {
      throw new MyError('myTopic cannot be empty');
    } else {
      let topic: string;
      topic = 'v1/items/' + myTopic.itemType + '/' + myTopic.itemID + '/'
        + myTopic.dataType + '/' + myTopic.dataTypeID;
      this.subscriptionTopicsMap[topic] = myTopic;
      this.client.subscribe(topic);
    }
  }

The error occurs at this line:

this.subscriptionTopicsMap[topic] = myTopic;

As someone new to typescript, I would appreciate any guidance on what might be going wrong here. Thank you for your advice.

Answer №1

My preferred method is a simpler approach that eliminates the necessity for an additional interface. Similar to the previous answer, you will require ={} as shown below:

private topicsRegistry: { [key: string]: MyTopic; } = {};
this.topicsRegistry[topic] = myTopic;

Answer №2

To ensure proper initialization, it is advisable to initialize your property when declaring it:

//private subscriptionTopicsMap: StringTopicToMyTopicMap;
private subscriptionTopicsMap: StringTopicToMyTopicMap = {};

Answer №3

Make sure to initialize your subscriptionTopicsMap dictionary, Additionally, ensure that you have a class which implements StringTopicToMyTopicMap and can be instantiated.

class StringTopicToMyTopicMapClass implements StringTopicToMyTopicMap {
    [topic: string]: MyTopic;
};

private subscriptionTopicsMap: StringTopicToMyTopicMap = new StringTopicToMyTopicMapClass();

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

Factors contributing to variations in performance among different types of iterators

Exploring the capabilities of JavaScript's new array functions, I noticed significant differences in performance with the code snippets below. Check out the comparison on jsfiddle: http://jsfiddle.net/jKUm5/ Slowest for var i in array (67.2ms): for ...

Having trouble with jquery onclick function not triggering

Having an unusual problem here. I've written a piece of code that allows users to generate and delete dynamic input elements. However, there seems to be an issue where clicking the remove button doesn't trigger the onclick event. <input typ ...

I am encountering a problem with validating my form using JavaScript

I've been working on a project where I'm developing a website using JavaScript, HTML, and CSS to search for movies and purchase tickets. While the basic functionalities are working fine, I'm encountering some challenges with form validation. ...

Enhancing functionality with extra JavaScript tags in next.js

Recently, I delved into programming with react & next.js after previously working with node.js. It didn't take long for me to create my first application, but upon inspecting the page, I noticed an abundance of extra JavaScript code (see image below). ...

What is the process of connecting JSON keys to one another?

I am currently brainstorming a solution to link two distinct JSON formats with their respective keys. Here are the two formats: { "price": [ 511, 499, 419, 312 ], "paid": "OK", "contract": "year", "begindate": "01/01/2018", " ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

Observing Array behaviors in TypeScript

Struggling to generate an observable from an array due to the recurring error message (A tuple type element list cannot be empty). Despite multiple attempts, I'm unable to resolve this issue. listDonationsHistory(): Observable<[]> { const ...

I need to access a directory that is outside of my current folder in Express.js

I have two folders within my main folder; one is for front-end and the other is for back-end. project ├── back-end │ ├── public │ └── routes │ ├── Calling.js │ └── index.js └── front-end ├ ...

Making an "associated" route the active route within Aurelia

In my Aurelia application, I have implemented two routes: a list route called Work and a detail route called WorkDetail. Currently, only the list route is visible in the navigation menu: Home | *Work* | Contact | . . . When users navigate to the W ...

Retrieving a Mat Icon through an Angular directive

Currently facing an issue with loading the icon component from Angular Material. My goal is to incorporate a clickable icon that clears the input using a directive, as seen below: <input appClearInput></input> The main problem lies in the fac ...

Adding a class to radio buttons with a specific label using jQuery

As of now, I am utilizing jQuery to apply or remove a class when a radio button is selected. However, the issue arises when it checks all radio buttons, resulting in CSS being added to only one radio button. My HTML layout consists of rows containing eith ...

What are the necessary peer dependencies for Angular-compatible projects?

In the process of integrating RxJS as a peer dependency for my Angular 6 project, I encountered an interesting declaration method. Take, for instance, angular/flex-layout, which declares its RxJS dependency in this manner: "requiredAngularVersion": ">= ...

What is the best way to send a lengthy JSON string using a GET/POST request on Internet Explorer 8?

Having an issue sending a lengthy JSON string from the front-end to PHP on the back-end. Unfortunately, IE8's 2,048 character limit is causing the request to get cut off, regardless of whether it's a GET or POST request. Any suggestions on how t ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

The beta version of Angular 2.0 introduces the BrowserDomAdapter for easy access to the DOM

I have a Component in Angular 2.0 that is attempting to utilize the DOM Adapter API from Angular's BrowserDomAdapter documentation. The initialization of this DomAdapter can be found here. However, I am uncertain about whether the Dom Adapter needs t ...

Node.js server utilizing Jade template variables

My goal is to display a contacts list using Jade code. I have transformed each contact div into Jade code, but now I need to populate the relevant fields. Can this be done on the server side? My server code is written in Node.js. Here is an example of the ...

Tips for displaying res.locals information in the console for debugging purposes using ExpressJS and Nodejs

Currently, I am delving into the world of Node.js and ExpressJS as a novice in this realm. My primary requirement is to log the entire or partial content of res.locals in my console for debugging purposes. Here's what I've attempted: var foo_ro ...

Out of the blue, I encountered an issue while trying to install Express in node.js using Types

Encountered a failure while attempting to install Express with node.js in Typescript. Received the following warning: https://i.sstatic.net/XcrGX.png Performed npm initialization, started index.js, created tsconfig.json, and installed ts-node. The comman ...

Error: User authentication failed: username: `name` field is mandatory

While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am followi ...

What is the process of importing types in TypeScript?

Here is the export I am working with: import * as jwt from 'jsonwebtoken'; ... export type MyJsonWebToken = typeof jwt; Next, when attempting to use it in my code: export class AuthService { constructor( @Inject(constants.JWT) private ...