The element is implicitly assigned an 'any' type due to the fact that a 'string' expression cannot be used to access data in the 'ProductMapData' type

In my sortDynamic function, I am attempting to dynamically sort data like this:

 const sortDynamic = (key: string, order: string) => {
    const sortOrder = order === 'asc' ? 1 : -1;
    return (a: ProductMapData, b: ProductMapData) => {
       const A = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key];
       const B = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key];
       if (A < B) {
          return sortOrder * -1;
       } else if (A > B) {
          return sortOrder * 1;
       } else {
          return 0;
       }
    };
 };

The ProductMapData interface looks like this:

interface ProductMapData {
  advanceRevenue: number;
  advanceTickets: number;
  changeInPeriodRevenue: number;
  changeInPeriodTickets: number;
  currency: string;
  entityRef: string;
  eopAdvanceRevenue: number;
  eopAdvanceTickets: number;
  hallLabel: string;
  occurredAt: string | undefined;
  playedOffRevenue: number;
  playedOffTickets: number;
  relatedEventName: string;
  thumbnail: string;
  timeBegins: string;
  timedBeginsBegins: string;
  soldTickets: number;
  soldRevenue: number;
}

I am calling the function here:

productMapData.sort(sortDynamic('soldTickets', 'asc'));

However, I am encountering an error message that says

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProductMapData'. No index signature with a parameter of type 'string' was found on type 'ProductMapData'.ts(7053)
on a[key] and b[key]. I'm unsure of where the issue lies. Any assistance would be greatly appreciated.

Answer №1

Enhance your ProductMapData interface by extending it to another interface that enforces strict typing for the Key data type. You are free to specify the data type for the value as well.

Check out the strict interface definition for ProductMapData below, where you can include additional value types as needed:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

To ensure that your object keys are of type string only, simply extend your existing ProductMapData interface with IObjectKeys:

interface ProductMapData extends IObjectKeys

By doing this, you inform your instance that the keys in your object should be exclusively strings.

Experiment with this concept using the TypeScript Playground Link

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

Altering the parent component's output depending on a boolean value established in the child component within Angular

Recently I began learning Angular and find myself in need of some assistance when it comes to managing a specific situation with Angular 16. In our project, we have two different versions of the site header represented by two components - one as the defaul ...

After a cell editing event, there are times when the grid data is not saved properly due to

I have integrated the ag-grid library into my project for data display. After editing a cell, I want to save the changes to the backend database by persisting the rowData. Most of the time, this process works smoothly, but occasionally I encounter an issue ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

Exploring the NestJS framework using mongoose schema, interfaces, and DTOs: A deep dive

As a newcomer to nestJS and mongoDB, I find myself questioning the need to declare DTO, schema, and interface for every collection we aim to store in our mongoDB. For example, I have a collection (unfortunately named collection) and this is the DTO I' ...

Creating a unique attribute in FabricJS object using TypeScript

Encountering a TypeScript error when trying to add a custom attribute to a new FabricJS object. How can I extend the IObjectOptions globally to include this custom attribute? const workarea = new fabric.Rect({ id: "workarea", width: 250, he ...

"Implementing a date picker in your Ionic 5 app: A step-by-step

How can I integrate a date picker similar to the Angular Material Date picker into my Ionic 5 application? I prefer not to use the native ion-datetime component due to limitations such as incomplete calendar display and lack of support for alternative ca ...

Can you explain the meaning of <T = {}>?

While browsing through the documentation, I came across this generic type: type GConstructor<T = {}> = new (...args: any[]) => T; https://www.typescriptlang.org/docs/handbook/mixins.html Above this line, there is a brief mention that it is a Gene ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Update the datalist in the view once the user has completed typing in the textbox using Angular 7

Struggling to automatically refresh a datalist in the view once the user finishes typing in the textbox and updates the results. I've experimented with angular directives, Observable, timeouts, and debounces without success. It seems like I've ex ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

The 'innerText' property is not present in the 'Element' type. (2339)

Recently, I've been working with javaScript and I encountered some issues while writing a function. Strangely, I kept receiving error messages that I couldn't quite understand. Initially, there was a problem where every time I tried to create a j ...

Tips for securely encrypting passwords before adding them to a database:

While working with Nest.Js and TypeORM, I encountered an issue where I wanted to hash my password before saving it to the database. I initially attempted to use the @BeforeInsert() event decorator but ran into a roadblock. After some investigation, I disc ...

Leveraging default values in generic implementations

Imagine a scenario where the following code is present: type QueryResult<ResultType = string, ErrorType = string> = { result: ResultType, } | { errors: ErrorType, } So, if I want to initialize my result, I can proceed like this: const myResult: ...

Error in Typescript: Draggable function is undefined

I'm currently working with typescript alongside vue and jquery ui. Encountering the error "TypeError: item.$element.draggable is not a function". What am I doing wrong in my code? I have already included jquery-ui, as shown in the following files. M ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Verify if the date and time in string format is the exact same as noon

In my data collection, there are multiple objects each containing a specific date and time value: [ {dt: "2019-11-29 12:00:00"}, {dt: "2019-11-29 3:00:00"}, {dt: "2019-11-29 6:00:00"}, {dt: "2019-11-30 12:00:00"}, {dt: "2019-11-30 6:00:00"} ] M ...