Tips on improving TypeScript code with dynamic variables for successful linting

Is there a proper way to refactor the creation of dynamic variables in TypeScript? I am encountering an error when trying to assign a value to obj.identifier which is not known. What would be the correct approach for refactoring this scenario?

interface test {
  [key: string]: any
}

class Test implements test {
  #obj: any
  constructor(obj: any) {
   this.#obj = obj
  }
  test(value: string) {
    // Type 'string' is not assignable to type '(value: string) => void'
    this[this.#obj.identifier as keyof Test] = value
  }
}

I'm looking to use it in the following way:

const t = new Test({identifier: "a"})
t.test("aa")
t.a 
=> "aa"

Answer №1

To solve the issue, I implemented a container object in my code.

interface ContainerType {
  prop1: any
  prop2: any
  prop3: any
}

class Example {
  container: ContainerType = {}
  ...
}

Next, I dynamically assigned properties and values to the container.

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

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

How to achieve dynamic class instantiation through constructor injection in Angular 8?

Despite my efforts to find a solution, my understanding of Dependency Injection in services is still limited, making it challenging to get this thing working. I'm left wondering if there's any way to make it work at all. My current setup involve ...

When using Angular, a service can be declared in the viewProviders of the parent component and then accessed in the viewProviders of the child

Imagine a scenario where there is a parent component called AppComponent, a directive named MyDirective, and a service named SimpleService. In this case, MyDirective is utilized in the template of AppComponent and injects SimpleService using the Host deco ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

The functionality of routerLink is not functioning as expected when used on button elements

My dashboard is designed to display information retrieved from Firebase. However, I am facing an issue with a button labeled as (more) that should redirect me to a specific page when clicked. Unfortunately, the button doesn't seem to be working as int ...

JavaScript library experiencing import issues with Typescript custom type

Working on a Vue project with TypeScript, I encountered an issue when importing a custom type created for the vue-numeral-filter package. The error message received is as follows: ERROR in /Users/bmartins/Development/app-invest/src/main.ts(14,30): 14:30 ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...

When Typescript Encounters Compilation Errors, Treat Them as Warnings Instead

After using npx create-react-app my-app --typescript to create my app, I want to set it up in a way that allows me to compile it even when there are typescript errors, so I can address them later. I couldn't find any compilerOptions for this. Is ther ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

I am looking to update the color based on the prop value in React

Currently using react along with typescript. My objective is to adjust the color based on the value passed through props. The props will contain either "primary," "secondary," or "brand" as a string type. When the value "primary" is provided, I aim ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

What causes the Babel JSON configuration error to appear in my project?

I'm currently working on a React website, utilizing TSX instead of JSX. In my setup, I am using webpack and Babel. However, I have encountered an error while running the webpack-dev-server. ERROR in ./src/index.tsx Module build failed (from ./node_mo ...

Returning self-referencing types in static methods within derived classes

Exploring the concept of Polymorphic this in TypeScript 1.7, which was brought to my attention in a thoughtful discussion thread I found on Stack Overflow, I came across an interesting way to define methods in a class with a return type of this. This has t ...

Struggling with importing aliases in TypeScript for shadcn-ui library

I am facing a challenge with resolving TypeScript path aliases in my project. I have set up the tsconfig.json file to include path aliases using the "baseUrl" and "paths" configurations, but alias imports are not functioning as intended. My goal is to imp ...

Encountering TypeScript error TS2339 while mocking a React component with Jest

When attempting to mock a React component using Jest, I encountered an issue where TypeScript was not recognizing the mocked methods and showing a TS2339 error. Below is the test code snippet causing the problem: jest.mock('./features/News/News' ...