Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
How to take tf.Tensor type to number type in Typescript

I'm working with Tensorflow.js in typescript and I want to get the cosine similarity of two 1D tensors, but I am having trouble with dealing with the types that tensorflow uses. When I calculate the cosine similarity, using this function I should be getting a number, but instead I get a bunch of different other types including number.

function calculateCosineSimilarity(abstractEmbedding: tf.Tensor1D | Array<number>, queryEmbedding: tf.Tensor1D | Array<number>): number{
    const dotProd: tf.Tensor = tf.dot(abstractEmbedding, queryEmbedding);
    const lenAbstractEmbedding: tf.Tensor = tf.dot(abstractEmbedding, abstractEmbedding);
    const lenQueryEmbedding: tf.Tensor = tf.dot(queryEmbedding, queryEmbedding);
    const similarityScore: tf.Tensor = tf.div(dotProd, tf.mul(lenAbstractEmbedding,lenQueryEmbedding));
    return similarityScore.arraySync(); 
}

I get this error at the return statement:

Type 'number | number[] | number[][] | number[][][] | number[][][][] | number[][][][][] | number[][][][][][]' is not assignable to type 'number'.

I know when you take dot products of multidimensional arrays, the dimensions/types of the resulting array will vary, but for my case I know I will be getting a single value back, so I just want to return a single number. Is there a way to resolve this issue without having to change the return type of the function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I don't believe it is the best practice, but if you do not want the return type of the function to list all of those type options, or be Any, then you can force the coercion of the response variable to unknown, if necessary, and then to the type you are expecting.

return similarityScore.arraySync() as number;

or if the types do not sufficiently overlap

return similarityScore.arraySync() as unknown as number;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!