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 =, queryEmbedding);
    const lenAbstractEmbedding: tf.Tensor =, abstractEmbedding);
    const lenQueryEmbedding: tf.Tensor =, 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?


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;

Answered By – dscarlin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published