The 'ISortPriority<any>[]' parameter type argument cannot be assigned to the parameter type

In order to properly sort an array based on assigned keys, I have implemented the ISortPriority interface. Although my sorting algorithm is functioning correctly, I am encountering difficulties when it comes to utilizing the interface.

Here is an example of the test I am conducting:

it('Should sort with multiple keys - Numbers', () => {
    const arr = [{name: 'j company', title: 'Software Eng 1', age: 23,company: 'test'}, {name: 'f company', age: 21, title: 'Software Eng 7', company: 'abc'},{name: 'g company', title: 'Software Eng 2', age: 22, company: 'test'}, {name: 't company', age: 24, title: 'Software Eng 3', company: 'test'}];
    const keys: ISortPriority<any>[] = [{sortKey: 'age', priority: 1}, {sortKey: 'company', priority: 3}, {sortKey: 'name', priority: 4}, {sortKey: 'title', priority: 5}];
    expect(sortArrayByKey(arr, keys)).toEqual([{name: 'f company', age: 21, title: 'Software Eng 7', company: 'abc'}, {name: 'g company', age: 22, title: 'Software Eng 2', company: 'test'}, {name: 'j company', age: 23, title: 'Software Eng 1', company: 'test'}, {name: 't company', age: 24, title: 'Software Eng 3', company: 'test'}]);
});

However, upon calling:

expect(sortArrayByKey(arr, keys))

An error message pops up stating: "Argument of type 'ISortPriority[]' is not assignable to parameter of type '"title" | "name" | "company" | "age"'." when hovering over the "keys" parameter.

Lastly, here are the sorting method and interface that I am employing:

export function sortArrayByKey<T>(ordersArr: T[], sortByKeys: keyof T): T[] {
    return ordersArr.sort((a, b) => {
    return sortWithKey(a, b, sortByKeys, 0);
});
}

function sortWithKey<T>(a: T, b: T, keys, index: number) {
    index = index || 0;
    keys = keys.sort((c, d) => (c.priority > d.priority) ? 1 : -1);
    const currKey = keys[index].sortKey;
    return a[currKey] > b[currKey] ? 1 : (a[currKey] < b[currKey] ? -1 : 
    sortWithKey(a, b, keys, index + 1));
}


export interface ISortPriority<T> {
    priority: number;
    sortKey: keyof T;
}

Answer №1

One thing that stands out to me is the discrepancy in the type declaration for sortByKeys parameter in the code snippet below.

export function sortArrayByKey<T>(ordersArr: T[], sortByKeys: keyof T): T[] {
    return ordersArr.sort((a, b) => {
        return sortWithKey(a, b, sortByKeys, 0);
    });
}

While you specify that sortByKeys should be of type keyof T, in the code implementation you are attempting to pass it ISortPriority[].

I suggest making the following adjustments to rectify this issue:

export function sortArrayByKey<T>(ordersArr: T[], sortByKeys: ISortPriority<T>[]): T[] {
    return ordersArr.sort((a, b) => {
        return sortWithKey(a, b, sortByKeys, 0);
    });
}

function sortWithKey<T>(a: T, b: T, keys: ISortPriority<T>[], index: number) {
    index = index || 0;
    keys = keys.sort((c, d) => (c.priority > d.priority) ? 1 : -1);
    const currKey = keys[index].sortKey;
    return a[currKey] > b[currKey] ? 1 : (a[currKey] < b[currKey] ? -1 : 
    sortWithKey(a, b, keys, index + 1));
}

The main modifications include changing the type of sortByKeys parameter in the first function and the keys parameter in the second function to both be ISortPriority[].

This adjustment should address the issue at hand.

Answer №2

The parameter that you need to focus on in the sortArrayByKey function is:

sortByKeys: keyof T

This parameter specifically requires one of the 4 keys from the objects you are providing in the first argument - title, name, company, or age.

It seems like there may have been a mistake in how you entered this parameter, as it appears you included all keys with their priorities. The correct signature for sortArrayByKey should look something like this:

function sortArrayByKey<T>(ordersArr: T[], sortByKeys: ISortPriority<T>[]): T[] 

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

Having trouble adding custom props to MUI-Material ListItemButtonProps? Facing a TypeScript error?

This particular task should be relatively straightforward. I am seeking a custom component that inherits all props from ListItemButtonProps, while also adding an extra state prop: type SidebarListItemButtonProps = ListItemButtonProps & { state: Sideb ...

Angular 9 npm is encountering an issue with 'bindings' and is unable to find the 'fs' module. It is presenting a resolution error

I've been struggling to compile my angular project for days now, as the bindings npm package is unable to locate fs, which I suspect is a webpack issue within Angular. Despite finding some suggestions on Github and Stack Overflow advising me to add th ...

Exploring Ngrx: Leveraging a single selector to choose multiple property modifications

I need some help with my reactive Form Angular application that uses the NGRX store. Instead of subscribing to the entire state, I want to subscribe to changes in specific fields like "name" and "city." I have been attempting to use the selector selectFor ...

merge the states of two Redux stores

I have two different stores in my system - one for properties and another for owners. Each property can be owned by one or more owners, and I need to organize the properties based on their respective owners, essentially creating a map structure like Map< ...

Instead of TypeScript, Webpack produces JavaScript source maps

Currently, I am developing a TypeScript application (Angular 11) and using Webpack for code bundling. The issue I am facing is related to generating a source map with Webpack. While the source map is being generated for the JavaScript code as intended, it& ...

Step-by-step guide to configuring Angular 2 in Visual Studio 2013

Struggling to set up Angular 2 in Visual Studio 2013 without any external web tools? Even after following the Angular2 Quick Start guide, I couldn't get it to work. Is tsconfig.json supported in VS 2013? Any assistance or helpful links would be grea ...

Please insert text into the dropdown selection option

Is there a way I can include an input text field at the bottom of a select dropdown? <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option> &l ...

Using conditional statements to localize in Angular

In my Angular application, I am utilizing i18n for internationalization purposes. When it comes to HTML, I use i18n="@@<unique_Id>" and for dynamic elements defined in TypeScript class files, I use $localize. For example: this.buttontext = ...

The element ion-view is not recognized

Here is the content I have for my Ionic page: <ion-content padding class = ""view-content"> <form> [form content here...] </form> </ion-content> This is the CSS code from my file: .view-content { backg ...

What is the best way to determine the return type of a function based on the return type of its callback?

In the code snippet below, we have an interface that defines a function which takes a callback function and returns the value returned by the callback. export interface MonitoredOperation { <T = any>(operationName: string, operation: () => T ...

Utilizing CucumberJs, Protractor, and TypeScript to Implement Dynamic Tags/Variables in .feature Files

Currently, I am facing a challenge where I have multiple environments with various features enabled. My goal is to streamline the CI/CD process by leveraging the available variables. Is it possible to automate this process by dynamically reading these va ...

What could be causing the error message "Unable to access property 'createComponent'?"

The code in its entirety: export class FileSaveDialogComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild("target", { read: ViewContainerRef, static: true }) target; ngAfterViewInit() { console.log(this.target); const compo ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

Implement SSL Encryption for IONIC Mobile Apps or Angular Web Applications

I am just beginning my journey in this field. Currently, I am using the IONIC framework to develop an application. The backends, which include authentication, storage, and a database, are hosted on Firebase. Additionally, I utilize some third-party APIs a ...

Are you looking to use the 'any' type instead of the 'Object' type? Angular Services can help you with that

I encountered the following error message: Argument of type 'OperatorFunction<APISearch[], APISearch[]>' is not assignable to >parameter of type 'OperatorFunction<Object, APISearch[]>'. The 'Object' type is ...

Dealing with Errors in Angular 8: Best Practices for Handling Response Errors

When an error is thrown from the WEB API, I do not receive any response and the debugger does not hit. However, in case of success, I do get a response and the debugger hits. All I want is to receive an error response and have the debugger hit every time, ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Retrieving the Final Value from an Observable in Angular 8

Is there a way to retrieve the most recent value from an Observable in Angular 8? let test = new BehaviorSubject<any>(''); test.next(this.AddressObservable); let lastValue = test.subscribe(data=>console.log(data.value)); Despite my ef ...

The typical toggle function may not function efficiently in conjunction with the setState() method

In my current project, I have a state that defines an interface like this: MyState { variableOne: string; variableTwo: boolean; variableThree: boolean; // ... } There's also a toggle function in the code: toggleFunction = (value: keyof MyS ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...