Navigating through unidentified object in Typescript

I'm working with an object that has an unknown format, specifically a users' CSV file. My task is to iterate through the keys to identify certain keys, such as phone numbers referenced as phoneNumbers1, phoneNumbers2, and so on in the .csv file.

How can I eliminate the //@ts-ignore without facing any backlash? :)

        const phoneNumbers = Object.keys(data)
          //@ts-ignore
          .filter((key) => key.includes("phoneNumbers") && !!data[p])
          //@ts-ignore
          .map((p) => ({ number: data[p], type: PHONE_TYPES.OFFICE }));

While attempting to access the information using data[p], I encounter the following error:

Element implicitly has an 'any' type because 
expression of type 'string' can't be used to index type 'object'.

PS: data is of type object. At this point, I only know it is indeed an object (parse was successful), but the contents are still unknown.

I am aware that I could resort to using any or other workarounds, but I am seeking a more elegant solution.

Answer №1

object doesn't fit the bill here. The object type basically represents an empty object like {}, which doesn't allow for access to keys that are non-existent.

It might be more appropriate to use a type such as Record<string, unknown>. This type of object allows access to any string key and returns an unknown type.

If dealing with CSV data, you could also consider using Record<string, string> if all values are known to be strings.

With these adjustments, your code should compile error-free:

const data: Record<string, unknown> = { whoKnows: 'foo' }

const phoneNumbers = Object.keys(data)
  .filter((key) => key.includes("phoneNumbers") && !!data[key])
  .map((p) => ({ number: data[p] }));

Take a look at the playground

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 only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

The ValidationPipe does not function properly when utilizing app.useGlobalPipes

Hello! I'm looking to implement the ValidationPipe globally using useGlobalPipes. Currently, my code looks like this: import 'dotenv/config'; import {NestFactory} from '@nestjs/core'; import {ValidationPipe} from '@nestjs/com ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers. public productsWithTeasers: (Product | Teaser)[]; When attempting to iterate through this array, an error is thrown in VS Code. <div *ngFor= ...

Despite passing the same dependency to other services, the dependencies in the constructor of an Angular2 Service are still undefined

To successfully integrate the "org-agents-service" into the "org-agents-component," I need to resolve some dependencies related to the required api-service. Other components and services in the hierarchy are also utilizing this api-service, which acts as a ...

Deleting the last item from an array in Typescript

Consider the following array : ["one-", "two-", "three-", "testing-"] Once converted into a string, it looks like this: "one-,two-,three-,testing-" I need to remove the last character (hyphen) after 'testing' and create a new array from it. ...

Filter a data array using a two-dimensional filter array that may change dynamically

Currently, I am facing a challenge where I need to filter a data array of objects using a two-dimensional filter array of objects. Here is a glimpse of my data array: dataArray = [{ Filter_GroupSize: "1" Filter_Time: "5-30" title: "Tools Test ...

Incorporate a typescript library into your Angular application

Recently, I added a text editor called Jodit to my angular application and faced some challenges in integrating it smoothly. The steps I followed were: npm install --save jodit Inserted "node_modules/jodit/build/jodit.min.js" in angular.json's bui ...

Updating tooltip text for checkbox dynamically in Angular 6

Can anyone help me with this code? I am trying to display different text in a tooltip based on whether a checkbox is active or not. For example, I want it to show "active" when the checkbox is active and "disactive" when it's inactive. Any suggestions ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

Dealing with Cross-Origin Resource Sharing problem in a React, TypeScript, Vite application with my .NET backend

I'm encountering a CORS issue when trying to make a Request using Fetch and Axios in my application hosted on the IIS Server. Here are my Server API settings: <httpProtocol> <customHeaders> <add name="Access-Control-Allow-O ...

Issues with implementing the link component in next.js

I've been working on a blog using next.js and I'm having trouble with the header links not working. I followed the next.js documentation to create the links, but whenever I reload the website and try to click the links, my console shows: "GET 40 ...

The value of type 'number' cannot be assigned to type 'string | undefined'

Having an issue with the src attribute. I am trying to display an image on my website using the id number from an API, but when I attempt to do so, it gives me an error in the terminal saying 'Type 'number' is not assignable to type 'st ...

Ways to enhance TypeScript definitions for Node.js modules

Using the nodejs module "ws", I installed typings using typings i dt~ws import * as WebSocket from "ws"; function add(client:WebScoket){ let cid = client.clientId; } I am trying to Expand the WebSocket object with a property called clientId, but I&a ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

What causes the distinction between entities when accessing objects through TestingModule.get() and EntityManager in NestJS?

Issue: When using TestingModule.get() in NestJS, why do objects retrieved from getEntityManagerToken() and getRepositoryToken() refer to different entities? Explanation: The object obtained with getEntityManagerToken() represents an unmocked EntityManag ...

When the variable type is an interface, should generics be included in the implementation of the constructor?

Here is a code snippet for you to consider: //LINE 1 private result: Map<EventType<any>, number> = new HashMap<EventType<any>, number>(); //LINE 2 private result: Map<EventType<any>, number> = new HashMap(); When the ...

Move after a specified amount of time

I'm struggling to implement a 6-second redirect in my Angular application that will take users to the homepage. The only resources I've found on this topic are for AngularJS. --------------------UPDATE--------------- Here are my current routes: ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...