vue3+ts 使用parseInt报错Argument of type ‘number‘ is not assignable to parameter of type ‘string‘.

Scenes

在之前习惯使用javascript开发的时候,直接使用parseInt将数字转为整数。而在使用typescript开发时,却出现了报错。
报错内容:Argument of type 'number' is not assignable to parameter of type 'string'.

Error reason

parseInt(string, radix) 函数解析字符串并返回整数。第一个参数为要解析的字符串,第二个参数为要转换的进制基数,默认为十进制。
javascript里会自动对参数进行隐式转换,因此使用parseInt(100)并不会报错,而typescript时报错了。

solution

1. toString is converted to a string

const data = parseInt((Math.random() * num).toString());

2. Use the Math.floor() method

const data = parseInt(Math.floor((Math.random() * num)));

Guess you like

Origin blog.csdn.net/zhongxiajiu/article/details/130624283