简体   繁体   English

如何在 Typescript 中将字符串转换为数字?

[英]How to convert string to number in Typescript?

I have a const inherited from another component that looking at its typeof, is a string.我有一个从另一个组件继承的 const,它查看它的 typeof,是一个字符串。 In javascript my code looks like this:在 javascript 我的代码如下所示:

Here I display a number, eg 24%这里我显示一个数字,例如 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:我现在尝试将此代码更改为 typescript 并且我执行了以下操作:

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算术运算的左侧必须是“any”、“number”、“bigint”类型或枚举类型。

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算术运算的左侧必须是“any”、“number”、“bigint”类型或枚举类型。

What am I doing wrong?我究竟做错了什么? What is the way to pass this code correctly to typescript?将此代码正确传递给 typescript 的方法是什么?

Thanks if can someone help me!!谢谢如果有人可以帮助我!

You need to parse the string to a number before you multiply it:您需要先将字符串解析为一个数字,然后再将其相乘:

{Number(progression) * 100}%

And

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM