Home > other >  Is there a work around for Operator ‘ ’ cannot be applied to types 'string | number' and &
Is there a work around for Operator ‘ ’ cannot be applied to types 'string | number' and &

Time:01-08

Background is I’m calling a function within a function that can either return a string or a number, and want to add that to another value. But am running into that error.

I’ve tried doing a check

function addNumbers(obj):number | string {
 const returnedValue = helperFunction(obj.blah) //this could be a number or string
 if (Number.isNaN(returnedValue) === false) {
  return returnedValue   anotherValue;
 }
 return ‘-’;

I assumed the Number.isNaN would get rid of the error but it didn’t. Any thoughts?

CodePudding user response:

Number.isNaN checks specifically for the value NaN. NaN is a special number that's returned by computations like 0/0. Most numbers and all strings will cause Number.isNaN to return false, and so the type is not narrowed down to exclude strings.

Instead, I recommend you do this:

if (typeof returnedValue === 'number') {
  return returnedValue   anotherValue;
}

CodePudding user response:

wrap the type with () eg: (number | string)

however it'll still fail as you return null at the end as well

so your return type should be (number | string | null)

  •  Tags:  
  • Related