Error in Typescript: The argument 'T' cannot be assigned to the parameter of type 'number'

Could someone help me diagnose the typescript error in this code snippet?

public sortList<T>(data: T[], key: string, action: boolean): Observable<T[]> {

const outputData: T[] =  data.sort((a, b) => {
  if (isNaN(a) && isNaN(b)) {
    return a[key].toUpperCase() > b[key].toUpperCase() ? 1 : a[key].toUpperCase() < b[key].toUpperCase() ? -1 : 0;
  }
});

return of(outputData)
  .pipe(
    share()
  );
}
}

The error related to 'isNaN(a)' and 'isNaN(b)' is as follows:

(parameter) b: T
Argument of type 'T' is not assignable to parameter of type 'number'.ts(2345)

Answer №1

It is not recommended to use the juggly-version of isNaN, but I understand that you are using it to check both type and NaN in your situation. While this method works with some juggling, a more reliable approach is to use type checking for types and NaN checking specifically for NaNs.

The initial console log outputs (1 - 3) demonstrate the behavior of isNaN. In the following section (4 - 6), I demonstrate the inverted equivalents of type checks.

The last part (7 - 8) illustrates the implementation of type-and-NaN checking. By this point, you are no longer dependent on the questionable behavior of isNaN and can switch to either the global version (since you now know you have a number) or the stricter Number.isNaN version.

The belt-and-braces method does not trigger any compiler warnings.

const num = 1;
const str = 'string';
const obj = { key: 'value' };

// It technically functions but causes compiler warnings

console.log('1.', isNaN(num)); // false
console.log('2.', isNaN(str)); // true
console.log('3.', isNaN(obj)); // true

// More focused on types (note the results are opposite as I'm displaying the "positive" test)

console.log('4.', typeof num === 'number'); // true
console.log('5.', typeof str === 'number'); // false
console.log('6.', typeof obj === 'number'); // false

const a = 1;

if (typeof a === 'number') {
    console.log('7a.', isNaN(a)); // false
    console.log('7b.', Number.isNaN(a)); // false
}

const b = NaN;

if (typeof b === 'number') {
    console.log('8a.', isNaN(b)); // true
    console.log('8b.', Number.isNaN(b)); // true
}

Below is a version that distinguishes between strings and numbers:

function stringNumberCheck(strNum: string | number) : boolean {
    const numeric = +strNum;
    return (typeof numeric === 'number' && !Number.isNaN(numeric));
}

console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false

Demo

"use strict";
function stringNumberCheck(strNum) {
    const numeric = +strNum;
    return (typeof numeric === 'number' && !Number.isNaN(numeric));
}
console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false

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

Extract the content of a nested JSON object in ReactJS using map function

I am encountering an issue while attempting to map nested JSON data, specifically the error 'Element implicitly has an 'any' type'. The problem arises within the search component at: Object.keys(skills[keyName]).map() Below is the cod ...

Oops, there was an error: Sorry, but we couldn't find any routes that match the URL segment 'edit/2'

My Angular4 app is functioning well, but I encountered the following error: :1440 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'edit/2' Error: Cannot match any routes. URL Segment: 'edit/2' at A ...

Sending a parameter to a route guard

I've been developing an application that involves multiple roles, each requiring its own guard to restrict access to various parts of the app. While I know it's possible to create separate guard classes for each role, I'm hoping to find a mo ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

Error: Module not located - Unable to resolve 'crypto'

Upon running ng serve, I encountered a list of errors that need to be addressed. Here is my package JSON configuration: { "name": "ProName", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "tes ...

What could be causing the HTTP PUT requests to stop functioning properly after a number of requests?

Currently, I am developing an app for the premier league that allows users to create their own teams, input scores for matches, and view updated team statistics in a sortable table based on the Premier League rules. Issue: I have encountered a problem wi ...

Communication between Angular components

My question is exactly as the title suggests. Let me explain what I need to do. Currently, I have a component widget. Whenever I click on this widget, a modal pops up with several items inside. Each item corresponds to a different section within the main ...

Issues arise when trying to implement an AngularJS 1.5 component using TypeScript

I recently tried creating an AngularJS 1.5 component using TypeScript, but unfortunately, it's not functioning as expected. The data binding seems to be completely broken. Although I can see the data in my console when the $onInit function fires, none ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Angular 6 asynchronous validator

I am trying to validate the availability of a username by typing it into a form field and checking with a REST API. My validation is done using Angular forms and validators. When I make a request to the backend, I receive true if the username exists and fa ...

Distribute your SolidJS Typescript components on npm

Recently, I developed a SolidJS TypeScript UI component and successfully published it to the npm registry. The project structure is organized as follows: |-app |-index.html |-src |-index.tsx |-App.tsx |-utils |- ... |-com ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Bypass Auth0 HttpInterceptor based on certain conditions

During the transition from Firebase to Auth0, my Angular front-end application authenticates users to either Firebase or Auth0 based on their email address. I am working on configuring the Auth0 AuthHttpInterceptor provided in the Auth0 Angular SDK for SPA ...

What sets React.FC<T> apart from Function() in TypeScript?

Do arrow functions and function notations differ from each other? It seems like these two methods function in the same way. One is written as React.FC<T> while the other as Function(). Is this simply a matter of notation, or are there deeper reaso ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

Service injected with karma testing

I'm currently facing an issue while testing a component that has a service injected with a HTTP POST method. When I try to run the test using Karma, I encounter the following error message: TypeError: Cannot read property 'response' of unde ...

Executing the http.put request twice in Angular2 will result in duplicate data being sent

I'm currently facing an issue with updating a company record through an API in my Angular 2 application. Upon debugging, I noticed that the http call is being triggered twice. I came across a similar discussion on Stack Overflow where the solution was ...

Develop a simple server with NodeJS, Express, and TypeScript to handle the following tasks in separate API endpoints within the same app.ts file

PS E:\Nodejs Training\Project_1> npm run build [email protected] build tsc PS E:\Nodejs Training\Project_1> npm run start [email protected] start node dist/node app.js node:internal/modules/cjs/loader:1147 throw er ...

Enhance Vuetify functionality using TypeScript for custom components

I'm facing a challenge with extending a Vuetify component and setting default props in TypeScript. While I had success doing this in JavaScript, I am struggling to do the same in TS. Below is an example of how the Component was implemented in JS: imp ...

Implementing one-way binding to an <input> in Angular 2 using ngrx/store

When utilizing one-way binding with [ngModel] on an <input>, typing characters into the input will always add characters to the value of the <input>. The issue arises when the [ngModel] expression continues returning its current value, as the & ...