How can we strengthen the type checking when defining the sorting function for json properties?

When dealing with a json structure from a service that contains .attributes json values, I often find myself needing to sort either by id from the DTO or by several attributes from the IContactsAttributes. The microservice returns this specific structure:

export interface IContactsDto {
  _links: ILink,
  attributes: IContactAttributes,
  id: number,
  lastUpdated: Date;
  createdOn: Date;
  localCreatedOn: Date;
  whoUpdated: number;
  location_id: number;
}

export interface IContactAttributes {
  contactIsAdmin: boolean;
  contactIsOperations: boolean;
  contactIsMarketing: boolean;
  contactLastName: string;
  contactFirstName: string;
  contactTitle: string;
  contactEmail: string;
  contactPhone: string;
}

It all works fine until I move this function to a library with strong type checking enabled and encounter the following error:

Error: src/app/microServices/dictionariesService.ts:102:32 - error TS2345: Argument of type '0 | ((a: any, b: any) => 0 | 1 | -1)' is not assignable to parameter of type '(a: any, b: any) => number'. Type 'number' is not assignable to type '(a: any, b: any) => number'.

102 return super.getAll().sort(this.sortService.sortCompareAscending('id', false, IJsonTypes.isNumber)); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

getAllSortedByInterfaceName() {
    return super.getAll().sort(this.sortService.sortCompareAscending('contactsLastName', true, IJsonTypes.isString));
  }

You can see the compare function below:

sortCompareAscending(prop, isAttribute, jsonType: IJsonTypes) {
    // Code for sorting
  }

Intellij suggests it should look like this:

return function(a: { [x: string]: { toLowerCase: () => number; }; }, b: { [x: string]: { toLowerCase: () => number; }; }) {

I've tried implementing that suggestion but the error persists. Can anyone provide guidance on how to define sortCompare with strong type checking enabled? Thank you for your assistance.

Answer №1

It seems the compiler always has the final say - here's a tip for anyone who might find this useful:

I encountered an interesting situation with a switch statement for different json types. Even though there was no possibility of falling through, the strict-typing compiler wasn't pleased with just returning 0 - which actually makes sense... somewhat

return function (param1: any, param2: any) {
          return 0;
        }

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

Enhancing your TypeScript version

Whenever I try to update my global version of TypeScript by running npm install -g typescript, the Angular project still shows an older version when I run ng v. Why does this happen and how can I ensure a consistent upgrade? https://i.stack.imgur.com/JzwK ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Guide to implementing ion-toggle for notifications with Ionic 2 and Angular 2

Currently, I am using a toggle icon to set the notification as active or inactive. The response is obtained from a GET call. In the GET call, the notification value is either 0 or 1, but in my TypeScript file, I am using noteValue as boolean, which means w ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Showing live reactive form elements simultaneously in Angular

Is there a way to display form elements/values individually as they are being entered by the user, rather than all at once using the JSON pipe? I'm struggling to figure out how to show each element separately in the HTML code. {{commentForm.value ...

Issue encountered while attempting to compare '[object Object]'. This operation is restricted to arrays and iterables

I'm puzzled by this error that keeps popping up in my code. The issue seems to be occurring in AppComponent.html:4. An error is appearing related to '[object Object]'. It seems that only arrays and iterables are allowed. app.component.ht ...

Inversify: class-based contextual dependency injection

I am currently experimenting with injecting loggers into various classes using inversify. My goal is to pass the target class name to the logger for categorization. The challenge I'm facing is the inability to access the target name from where I am c ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

Having trouble retrieving information from hash fetch fragment following authentication redirection in Angular 4

Once the authorization process is complete, the browser will be redirected to the following URL: &token_type=bearer&state=XYZ&expires_in=3599 However, just before I can retrieve the details, everything seems to disappear and the browser' ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

Exploring ways to expand the theme.mixins feature in MUI 5

Currently, I am in the process of updating Material UI from version 4 to 5 and encountering challenges with my existing theming. Since we are using typescript, it is important to include the appropriate types when extending themes. I intend to include th ...

Issue with default country placeholder in Ionic 6.20.1 when using ion-intl-tel-input

I have successfully downloaded and set up the "ion-intl-tel-input" plugin from https://github.com/azzamasghar1/ion-intl-tel-input, and it is functioning properly. However, I am facing an issue with changing the default country select box placeholder from " ...

experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType. I am encountering false and null tes ...

Introducing the concept of type-specific name inclusion

I am currently developing my Angular app using TypeScript with the goal of preventing redundancy through some form of generic handling. Here is where I am starting: class BaseProvider { api_url = 'http://localhost:80/api/FILL_OUT_PATH/:id&apo ...

Extract the variable from the URL path

Looking to retrieve a variable from the URL using Angular. In my routes configuration, I have the following: const routes: Routes = [ { path: ':page', component: BlogComponent} ]; Additionally, in my blog component's constructor, I have ...

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...