I am unable to access the object property in Typescript

Here is an object definition:

const parsers = {
  belgianMobile: (input: string) =>
    input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
};

Now, I want to access a property of this object using a key (for future use with multiple parsers):

const clean = cleanNumber(text);
  const [key] = Object.entries(validations).find(([key, regex]) => regex.test(clean));
  return ((parsers[key](text)) && parsers[key](clean)) || text;

However, TypeScript throws the following error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ belgianMobile: (input: string) => string; }'. No index signature with a parameter of type 'string' was found on type '{ belgianMobile: (input: string) => string; }'.

Answer №1

I have recently discovered that in order to retrieve data from a specific object, you must specify the object name like this:

const validations: { [key: string]: RegExp } = {
  belgianMobile: /^(0032|0)4\d{8}$/,
};

const parsers: { [key: string]: (input: string) => string } = {
  belgianMobile: input =>
    input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
};

Answer №2

It seems like you are looking for a solution similar to this.

const greeting: string = 'hello world';
const functions = [{
  formatNumber: (input: string) =>
    input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
},{
  formatNumber1: (input: string) =>
    input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '),
}];
console.log(functions[0].formatNumber(greeting));
console.log(functions[1].formatNumber1(greeting));

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 Primeng Angular2 checkbox malfunctioning issue

My form setup in Angular2 CLI looks like this: Inside the component export class UsersAddComponent implements OnInit { ngOnInit() { this.userForm = this._formBuilder.group({ role: ['', [Validators.required]], others: this._for ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript? I attempted to implement this solution, but it only affects the first element. ngAfterViewInit () { const matlabel = this.elRef.nativeElement.querySelecto ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Tips for dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

obtaining values from a JSON object and JSON array in java

I am struggling to generate a JSON string that combines both a JSON object and a JSON array. Here is the desired format: { "scode" : "62573000", "sname" : "Burn of right", "icd10" = [ {"icode" : "T25.229?", "iname" : "Right foot"}, {"icode" ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

I am interested in utilizing Vue Fallthrough attributes, but I specifically want them to be applied only to the input elements within the component and not on the container itself

I am facing an issue with my checkbox component. I want to utilize Fallthrough attributes to pass non-declared attributes to the input inside the checkbox component. However, when I add HTML attributes to the Vue component, those attributes are applied not ...

Combining multiple Observables and storing them in an array using TypeScript

I am working with two observables in my TypeScript code: The first observable is called ob_oj, and the second one is named ob_oj2. To combine these two observables, I use the following code: Observable.concat(ob_oj, ob_oj2).subscribe(res => { this.de ...

Using React to map and filter nested arrays while also removing duplicates

Hello, I recently started working with react and I've encountered a challenge while trying to map an array. const fullMen = LocationMenuStore.menuItems['menu']['headings'].map((headings: any) => { <Typography>{ ...

Discovering and Implementing Background Color Adjustments for Recently Modified or Added Rows with Errors or Blank Cells in a dx-data-grid

What is the process for detecting and applying background color changes to the most recently added or edited row in a dx-data-grid for Angular TS if incorrect data is entered in a cell or if there are empty cells? <dx-data-grid [dataSource]="data ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

In Angular 5, what is the best way to transform an array into an object and cycle through a list of

JSON: The JSON I have contains a list of userids that I want to iterate through, but I'm having trouble fetching the content in a list format. { "data": { "items": [ { "regions": "India", "owner ...

Error: In Angular Firebase, the type 'string' cannot be assigned to the type 'Date'

I am encountering an error. The following error is shown: "cannot read property 'toDate' of undefined. Without the toDate() | Date." After further investigation, I found: A Timestamp object with seconds=1545109200 and nanoseconds=0. A hel ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Why does the property of {{hero.name}} function properly in a <h> tag but not in an <img> tag?

Within this template, the code below functions correctly: <h3>{{hero.name}}</h3> It also works for: <a routerLink="/details/{{hero.id}}">{{hero.name}}</a> However, there seems to be an issue with the following image path ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Could I leverage a built-in function for comparisons when using React.memo?

I am utilizing a <Track/> component with an object as prop, similar to the following: const myData = { "location" : ["http://example.com/1.ogg", "http://example.com/2.mp3"], "identifier" : [" ...