Using a generic type that is a subclass of Number will trigger error TS2362 in TypeScript

Here is a code snippet that I am working on:

function reverse<T extends Number, D extends Number>(items: T[], m: D): T[] {
    var toreturn = [];
    for (var i = items.length - 1; i >= 0; i--) {
        (()=>{
            toreturn.push(items[i] * m);
        })();
    }
    return toreturn;
}

var sample = [1, 2, 3];
var reversed = reverse(sample, 10);
console.log(reversed);

My development environment has flagged 2 errors in this code:

Error:(5, 27) TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Error:(5, 38) TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

The issue stems from the fact that the entities being multiplied are not recognized as numbers or other valid types. I attempted to resolve this by specifying extends in the generic definition.

How can this issue be resolved?

You can find the relevant TypeScript Playground version here

Answer №1

It can be a bit bothersome, but due to the constraint on Number with a capital N, you must perform a type assertion to convert to both Number and then number:

(items[i] as Number as number) * (m as Number as number)

If this approach aligns with how the function is used, consider changing the generic constraint to just number instead of Number, making it simpler to assert to number. Perhaps generics aren't necessary at all for your use case? In that scenario, eliminate generics and replace types T and D with number.

The second generic constraint might not be needed since the type of m can simply be the base type without impacting the return type. Optimizing it could look like this:

function reverseAndMultiplyBy<T extends number>(items: T[], m: number): T[] {
    const toReturn = [];
    for (let i = items.length - 1; i >= 0; i--) {
        toReturn.push((items[i] as number) * m);
    }
    return toReturn;
}

Answer №2

By using type assertion, you can inform the compiler that you are certain these values will be numbers.

function invert<T extends number, D extends number>(elements: T[], factor: D): T[] {
    var result = [];
    for (var i = elements.length - 1; i >= 0; i--) {
        (()=>{
            result.push(<number>elements[i] * <number>factor);
        })();
    }
    return result;
}

var numbers = [4, 5, 6];
var invertedNumbers = invert(numbers, 7);
console.log(invertedNumbers);

Answer №3

if you utilized casting or assertion, check out the following Type assertions:

http://www.typescriptlang.org/docs/handbook/basic-types.html

information extracted from the provided link (basic-types.html):

Type assertions can be done in two ways. One is using the “angle-bracket” syntax:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

And another way is through as-syntax:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

function reverse<T extends number, D extends number>(items: T[], m: D): T[] {
    var toreturn = [];

    for (var i = items.length - 1; i >= 0; i--) {
        (()=>{
            toreturn.push(<number>items[i] * <number>m);
        })();
    }
    return toreturn;
}

var sample = [1, 2, 3];
var reversed = reverse(sample, 10);
console.log(reversed);

here


Update:

If using number on extend does not work, consider this solution:

toreturn.push( (<Number>items[i] as number) * (<Number>m as number) );

function reverse(items: T[], m: D): T[] {
    var toreturn = [];

    for (var i = items.length - 1; i >= 0; i--) {
        (()=>{
            toreturn.push( (<Number>items[i] as number) * (<Number>m as number) );
        })();
    }
    return toreturn;
}

var sample = [1, 2, 3];
var reversed = reverse(sample, 10);
console.log(reversed);

here

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

Issue with Typescript: The 'remove' property is not found on the 'EventTarget' type

I keep seeing the error Type error: Property 'remove' is not recognized on type 'EventTarget'. <img onError={function(e) { e.target.remove(); }} src="../me.jpg" alt=""/> ...

'map' is not defined in the current Typescript scope

As a newcomer to AngularJS, I am encountering an error when attempting to send a post request to my localhost server. The error message states [ts] cannot find name 'map' and cannot find name 'subscribe'. Any assistance in understanding ...

Modifying the state of one React component using another

Attempting to modify the state of one component using another component in ReactJs, however, being new to React. The parent component contains a state called: _SPCommandBarDisabled this.state = { _SPCommandBarDisabled: true } In a child component ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Scrolling the mouse wheel on Angular 2 Typescript Highcharts Highmap

I'm currently exploring if it's possible to subscribe to the zooming event in a Highmap using Angular 2 with Typescript for Highcharts/Highmap, or possibly even to a mouse wheel scrolling event. @HostListener('scroll', ['$event&a ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

Compilation issues in node-modules arise following the Vue package and i18next updates

Recently, I decided to upgrade from the i18n package to the newer version called i18next in my project. However, this update led to numerous errors popping up during compilation. Fortunately, by adding 'skipLibCheck' to the compiler options in th ...

Using the typescript infer feature does not function properly when dealing with arrays

My TypeScript code is causing some unexpected results: const myObject = { foo: ['a', 'b', 'c'] } type MyType = typeof myObject.foo extends [...infer Content] ? string : boolean The type MyType is coming out as 'string ...

React together with TypeScript presents a challenge where the scroll event type is not compatible with window.addEventListener

Could it be that TypeScript DOM event types and React Event types are not compatible with each other? Consider this code snippet: useEffect(() => { const onScroll = (event: React.ChangeEvent<Body>) => { console.log("event" ...

Creating a Typescript enum that implements interfaces can be achieved by first defining the enum

Creating a Typescript enum that implements interfaces I currently have these two enums All keys in enum ENNAME should only include keys from enum POSTAG export enum POSTAG { BAD = 0x80000000, D_A = 0x40000000, D_B = 0x20000000, D_C = 0x1 ...

Executing Dynamic SQL Queries in SQL Server

I've been working on developing a dashboard, and I've started the process of refactoring the application to make the database querying methods more generic and dynamic. Although I'm still relatively new to the concept of generics and consid ...

Generating an Object Using HttpClient

When working with httpclient, you can specify the type for the get call and receive a struct of that object. For example. http.get<ProductData>("url:ressource:id").subscribe(x=> this.myObj = x) This means that myObj will only appear to ...

Having trouble with the Typescript validator in my Angular IDE Eclipse Plugin - it doesn't seem

If i enter wrong code in typescript editor it doesn't show me any compile time error. I don't know why typescript validator doesn't work. I am using eclipse Neon.3 Release (4.6.3) with angular IDE plugin. Do i have to add anything further to ...

Using HttpClient to retrieve data in formats other than JSON

Error Encountered While Trying to Download Excel File via API I attempted to download an Excel file through an API using a specific method, but unfortunately, I encountered the following error: SyntaxError: Unexpected token P in JSON at position 0 at J ...

Customize the header text in PrimeNG

Is it possible to customize the header text with icons and more in this section? <p-accordion> <p-accordionTab header="Header 1"> Content 1 </p-accordionTab> <p-accordionTab header="Header 2"> Content 2 ...

Having difficulty generating a new object and implementing the export class feature in Angular 2

Here is the UserDetails class defined: export class UserDetails { name:string; phoneNumber:string; email:string; password: string; } Below is a service where userDetails are utilized:: import { Injectable } from '@angular/core'; import { Ht ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

How to retrieve an object of type T from a collection of classes that extend a common base type in Typescript

In my current project, I have a class named Foo that is responsible for holding a list of items. These items all inherit from a base type called IBar. The list can potentially have any number of items. One challenge I am facing is creating a get method in ...