I am not Fat
I am not Fat

Reputation: 447

how to convert a string array to number array?

I am trying to convert a string array to a number array A quick google search have lead me to this solution.

    let numbersAsStringArray = originalQueryParams[property] ?? []
    let numbers = numbersAsStringArray.map((i) => Number(i));

where I keep getting this i

Property 'map' does not exist on type 'string | string[]'.

numbersAsStringArray is just an simple array with a number in as a string.

Upvotes: 1

Views: 791

Answers (2)

Jinadee Yasiruka
Jinadee Yasiruka

Reputation: 51

You can try let numbers = Array.from(numbersAsStringArray,Number)

Upvotes: 0

853174
853174

Reputation: 128

It's a compilation error, not runtime error. Just tell TS that numberAsStringArray is of type string[] and it should be ok.

let numbersAsStringArray = (originalQueryParams[property] || []) as string[];
let numbers = numbersAsStringArray.map((i) => Number(i));

Upvotes: 3

Related Questions