2

I have an array that consists of a string and number ("2",3,4). I want to multiply the same and get an output of 24.

I tried this method but getting an error of "Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'."

var stringArray = ["2",3,4];
var numberArray = [];

length = stringArray.length;

for (var i = 0; i < length; i++)
  numberArray.push(parseInt(stringArray[i]));
console.log(numberArray);
2
  • I don't get this error and your code worked Commented Apr 27, 2022 at 8:08
  • In what context is this javascript being run? It works fine in the browser. Commented Apr 27, 2022 at 8:09

3 Answers 3

2

parseInt expects and argument of type string. However, since your array also contains numbers, you are calling it with a number, eg. parseInt(3), which is why you are getting the error.

A possible solution is to check manually and give a hint

var stringArray = ["2",3,4];
var numberArray = [];

length = stringArray.length;

for (var i = 0; i < length; i++) {
  let value;
  if (typeof stringArray[i] === 'string') {
     value = parseInt(stringArray[i] as string)
  } else {
     value = stringArray[i]
  }
  numberArray.push(value);
}
console.log(numberArray);
Sign up to request clarification or add additional context in comments.

1 Comment

A little variation using a for...of loop you can save a couple of lines and avoid using as thanks to type inference: tsplay.dev/WJq0Zm
1

Since you want to multiply.
var stringArray = ["2",3,4]; let res = stringArray.reduce((a,b) => a*b); the Reduce method will do conversion for you.

1 Comment

Thanks for the solution. I will check this out don't have much idea about Reduce method.
1

You can do it using the + operator like this:

var stringArray = ["2", 3, 4];

let res = 1;
for (var i = 0; i < stringArray.length; i++) {
  res *= +stringArray[i];
}

console.log(res);

1 Comment

Thanks for the solution this seems the simplest way to do it as well I can update the content dynamically as well if needed by this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.