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
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.