Home > Back-end >  Sum of two possible undefined numbers in typescript
Sum of two possible undefined numbers in typescript

Time:03-08

I'm trying to write a function that returns the sum of two attributes that can also be undefined. This is what I wrote:

function sumPossibleUndefinedValues(availability: T): number | undefined {
    const firstNumber = availability.first; //can be undefined
    const secondNumber = availability.second; //can be undefined

    return firstNumber !== undefined
        ? firstNumber   (secondNumber || 0)
        : secondNumber !== undefined
        ? secondNumber
        : undefined;
}

Now, I'm wondering if there's a better way to write this return statement.

CodePudding user response:

You can try that:

return firstNumber   secondNumber || firstNumber || secondNumber;

If the left side is undefined or NaN it tries the next one until secondNumber and in that case the value of secondNumber is returned.

CodePudding user response:

You can try this

return (availability?.first || 0) (availability?.second || 0)

  • Related