Issue: Multiplying values within an array in TypeScript requires that the left-hand side of the arithmetic operation must be of type 'any', 'number', or 'enum'

Having trouble with Typescript as I encounter this error message

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)

Specifically facing issues when trying to multiply values within an array. Attempting to create a function for calculating cosine similarity using the following code:

cosineSim(Q: string[], B: string[]){
    //var dotproduct = 0;
    let dotproduct: number= 0;
    var mA = 0;
    var mB = 0;
    for(var i=0; i< Q.length;i++){
      //The error goes here at Q[i] and B[i]
      //it says: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts
      dotproduct += Q[i] * B[i];
      mA += (Q[i] * Q[i]);
      mB += (B[i] * B[i]);
    }
    mA = Math.sqrt(mA);
    mB = Math.sqrt(mB);
    var similarity = (dotproduct) / ((mA) * (mB));
    return similarity;
  }

Trying to call this function in another piece of code like so:

var cos1 = this.cosineSim(eachdocTFIDF[0], eachdocTFIDF[1]);
console.log(cos1);

Here is an example of the data structure being passed:

//example value
eachdocTFIDF[0] = [0.5, 0.01123, 0, 0, 0.693215];
eachdocTFIDF[1] = [0.342131, 0.786785, 0, 0.2345, 0.00123];

Answer №1

function calculateCosineSimilarity(arr1: number[], arr2: number[]){
//let dotProduct = 0;
let dotProduct: number = 0;
let magnitudeA = 0;
let magnitudeB = 0;
for(let i=0; i< arr1.length;i++){
  //Issue occurs with arr1[i] and arr2[i]
  //Error message: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts
  dotProduct += arr1[i] * arr2[i];
  magnitudeA += (arr1[i] * arr1[i]);
  magnitudeB += (arr2[i] * arr2[i]);
}
magnitudeA = Math.sqrt(magnitudeA);
magnitudeB = Math.sqrt(magnitudeB);
let similarityIndex = (dotProduct) / ((magnitudeA) * (magnitudeB));
return similarityIndex;

}

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

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Customizing CSS in Angular Components: Taking Control of Style Overrides

I am new to working with Angular and HTML. Currently, I have two different components named componentA and componentB, each having their own .html, .css, and .ts files. In the componentA.css file, I have defined some styles like: .compA-style { font- ...

"Building a tree structure from a one-dimensional array in Angular: A step-by-step

I would like to implement a tree structure in Angular using flat array data and I am willing to explore different packages for rendering the tree. Users should be able to click on a node to view details such as node ID and title. The tree should initially ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Starting value within angular's toSignal()

Experiencing frustration with setting initialValue to true for a signal, encountering the error message (TS2769: No overload matches this call). The Observable does return an Observable. A workaround was found by omitting the "initialValue" option and ad ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Creating Algorithms for Generic Interfaces in TypeScript to Make them Compatible with Derived Generic Classes

Consider the (simplified) code: interface GenericInterface<T> { value: T } function genericIdentity<T>(instance : GenericInterface<T>) : GenericInterface<T> { return instance; } class GenericImplementingClass<T> implemen ...

Input a new function

Trying to properly type this incoming function prop in a React Hook Component. Currently, I have just used any which is not ideal as I am still learning TypeScript: const FeaturedCompanies = (findFeaturedCompanies: any) => { ... } This is the plain fun ...

Setting up Storybook with Tailwindcss, ReactJS and Typescript: A comprehensive guide

What is the best way to configure Storybook to handle Tailwindcss styles and absolute paths? Just a heads up, this question and answer are self-documenting in line with this. It was quite the process to figure out, but I'm certain it will help others ...

Ways to simulate a dependent class in TypeScript & JEST without modifying constructor parameters to optional

Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller class that relies on a Service class. The connection between the two is established through the ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

Are child routes permitted to be utilized without the need for router outlets, specifically for tab contents within a main component?

Can different components be rendered for each tab in a tab menu without using router outlets? Within my parent component, there is a template containing a tab menu component with each tab item having an ng template associated with it. I have set the tabs p ...

Associate a unique identifier string with a randomly generated integer identifier by Agora

For my current web project, I am utilizing a String username as the UID to connect to the channel in an Agora video call. However, I now need to incorporate individual cloud recording by Agora into the project. The challenge lies in the fact that cloud r ...

I am currently working on a project using the most up-to-date version of Angular, and I encountered an issue where the property 'value' is not recognized on the type 'EventTarget'

When utilizing the $event with the onkeyup event and attempting to pass the input field's value to the filter Function, it is not functioning as expected. <div class="container mx-auto p-5"> <div class="searchBar"> ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

Challenges with using forRoot and other function calls in AOT compilation

Upon compiling my app, I am faced with the error message: "Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Declaran ...

Restrict the number of rows in a CSS grid

Hello there, I am in the process of creating an image gallery using CSS grid. Specifically, my goal is to initially show just one row of images and then allow users to click a "Show more" button to reveal additional images. You can see my progress here: ...

Tips for streamlining the use of http.get() with or without parameters

retrievePosts(userId?: string): Observable<any> { const params = userId ? new HttpParams().set('userId', userId.toString()) : null; return this.http.get(ApiUrl + ApiPath, { params }); } I am attempting to streamline the two http.get ca ...

Error in Radix UI encountered while attempting to use "react-accordion"

Trying to import the root component of a react accordion and then export it in my project with the name Accordion. However, I keep getting a type error that says Unsafe assignment of an `any` value. I've attempted to fix it by using the as keyword but ...