Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly initialize vector of number in Typescript

I’m having difficulties at initializing a variable with the value returned from a function.
The function is hosted here and it should return an array of numbers.
So I try to define my variable as

import {default as linspace} from '@stdlib/array-linspace'

var xvalues:number[] = linspace(0,10, 10)

And the IDE gives me an error because Type 'Float64Array' is missing the following properties from type 'number[]': pop, push, concat, shift, and 5 more.ts(2740)
So I checked what was actually being returned by the function with the following logs:

console.log(typeof linspace(0,10,10) )
console.log(typeof linspace(0,10,10)[0] )

And the types are in fact

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Object
number

Then why defining my variable as var xvalues:number[] is not correct?

>Solution :

The error message is telling you what type to use Float64Array:

let xvalues: Float64Array = linspace(0,10, 10)

(var shouldn’t be used in new code.)

That said, there’s no need for an explicit annotation, TypeScript will infer it for you:

let xvalues = linspace(0,10, 10)

Then why defining my variable as var xvalues:number[] is not correct?

Because number[] and Float64Array are different things. It’s true that a Float64Array contains number values, but it’s a different container than a standard array. It’s also worth noting you’d have gotten the same result logging a value from a Float32Array, an Int8Array, or any other typed array other than BigInt64Array even though the contain different kinds of numbers, because when you access a value in a typed array, it’s converted from its raw type (an 8-bit two’s complement number, for instance, in the case of an Int8Array) to the plain number type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading