Home > Enterprise >  How to convert string to number in Typescript?
How to convert string to number in Typescript?

Time:09-15

I have a const inherited from another component that looking at its typeof, is a string. In javascript my code looks like this:

Here I display a number, eg 24%

{parseInt(progression * 100, 10)}%

Here I display a progress bar

<Bar style={{ width: `${progression * 100}%` }} />

I'm trying to change this code now to typescript and I did the following:

I declared the typing:

interface ProgressionProps {
  progression: string;
}

Here where I should display the %, I put it like this:

{Number(progression * 100, 10)}%

But I have the error:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts

And also in the other code:

<Bar style={{ width: `${progression * 100}%` }} />

I got the same error:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts

What am I doing wrong? What is the way to pass this code correctly to typescript?

Thanks if can someone help me!!

CodePudding user response:

You need to parse the string to a number before you multiply it:

{Number(progression) * 100}%

And

<Bar style={{ width: `${Number(progression) * 100}%` }} />
  • Related