Amir
Amir

Reputation: 4770

Argument of type 'number' is not assignable to parameter of type 'string' when using parseFloat

I am getting a Argument of type 'number' is not assignable... error when I use parseFloat in my code. I have tried typing differenceBetweenDates as string | number and as any, as well as unitDateValue as string | number and any, but the error remains.

It's particualy confusing, because the error says cannot assign, and give me the variable differenceBetweenDates, when I'm not setting the variable in the code. differenceBetweenDates is underlined as an error, but I am actually assigning unitDateValue;

Here is the function in question:

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() );
  }

}

Upvotes: 3

Views: 9285

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174997

parseFloat only accepts strings in its first parameter. That's the error.

Since you've already got a number there, you don't need to call praseFloat on it. Just wrap in parenthesis and call .toFixed(1) on the result.

unitDateValue = (differenceBetweenDates / (1000 * 60 * 60 * 24)).toFixed(0);

Upvotes: 14

Related Questions