我在代码中使用parseFloat时,得到类型'number'的参数不可分配...错误我尝试将differenceBetweenDates键入string | number
和any
,将unitDateValue键入string | number
和any
,但错误仍然存在。
这特别令人困惑,因为当我没有在代码中设置变量时,错误说不能分配,并给我变量differenceBetweenDates。 differenceBetweenDates 下划线标注为错误,但实际上我指的是 unitDateValue ;
这是有问题的功能:
export default function processDate(): void {
let endDateValue: any = 10;
let startDateValue: any = 20
let unitDateValue: any;
let unit = 'day';
let differenceBetweenDates: any;
// diff() will return a number
differenceBetweenDates = endDateValue.diff(startDateValue);
if(differenceBetweenDates > 0) {
switch (unit) {
case 'day': {
// ERROR: Argument of type 'number' is not assignable to parameter of type 'string';
// ERROR: let differenceBetweenDates: any;
unitDateValue = parseFloat( differenceBetweenDates / (1000 * 60 * 60 * 24) ).toFixed(0);
// This works but is not what I want, I need to parseFloat
// unitDateValue = ( differenceBetweenDates / (1000 * 60 * 60 * 24) ).toFixed(0);
break;
}
case 'week': {
// ERROR: Argument of type 'number' is not assignable to parameter of type 'string';
// ERROR: let differenceBetweenDates: any;
unitDateValue = parseFloat( differenceBetweenDates / (1000 * 60 * 60 * 24 * 7) ).toFixed(1);
//Round up on .9
let unitDateValueArray = unitDateValue.split('.');
if(unitDateValueArray.length === 2 && unitDateValueArray[1] === '9') {
unitDateValue = Math.round( Number(unitDateValue) );
}
break;
}
}
console.log( Number(unitDateValue).toString() );
}
}
答案 0 :(得分:5)
parseFloat
仅接受第一个参数中的字符串。这是错误。
由于您已经有号码,因此您无需在其上拨打praseFloat
。只需括在括号中并在结果上调用.toFixed(1)
。
unitDateValue = (differenceBetweenDates / (1000 * 60 * 60 * 24)).toFixed(0);