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 convert string to number in Typescript?

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

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

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

>Solution :

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

{Number(progression) * 100}%

And

width: ${Number(progression) * 100}% }}

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