Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying any number with null should return null instead of 0 in typescript

I have a scenario where in C#,

decimal? x; // number
decimal? y; // null
c=x*y //c returns null

where in typescript

let x:number=null;
let y:number=12;
c=x*y //c returns 0

**How to get null instead of 0 in typescript ?

I need to set generic way instead of using ternary operator and checking both properties null and returning null.

Is there any compiler options I need to set in tsconfig.json ?**

like image 299
gary Avatar asked Mar 06 '23 10:03

gary


1 Answers

Why the result is zero in your case

Because in TypeScript/JS/ES, an arithmetic operation involving a number and null will cause null to be implicit converted to a number. And null gets converted to 0.

If you want the "C# null-swallowing" behavior, you indeed need to specify it explicitly :

let c = x === null || y === null ? null : x * y;

The 'natural' behavior in Typescript is the same as JavaScript / EcmaScript : if you have an operation with a number and null, null will be coerced to the number 0.

Is there any compiler options I need to set in tsconfig.json ?**

To my knowledge, there isn't, and there shouldn't be, because that's how arithmetic operations work in ES / JS, and TS has no reason to try changing the arithmetic rules of ES towards the one used by C#.


I need to set generic way instead of using ternary operator and checking both p> properties null and returning null.

Another solution with NaN / undefined

To avoid this code cluttering and have a similar "some special values swallows every operation" like null in C#, you could maybe use NaN (Not a Number) instead of nulls.

This

  1. would be easy to just transform every null into NaN.

  2. any operation like x * y will give NaN if any operand is NaN, without any change to the code that performs computations.

  3. If you really need nulls at the end then you can convert back NaNs to null. (be careful, to test for a number to be NaN, use Math.IsNan(), never try to compare with === NaN as this will always give false, even NaN === NaN)

  4. As a last but not least remark, if one of the operand is undefined, the result of an operation will also be NaN. So actually, you could as well turn your nulls to undefined instead of NaNs, the conversion from C# null to JS/TS undefined might be more natural. Might be easier on the serialization side as well (hint : Newtonsoft.Json.NullValueHandling.Ignore)

It is not sure this can be adapted to your situation, but it's worth checking if you want to avoid cluttering your code with conditionals like I wrote above.

like image 106
Pac0 Avatar answered Mar 09 '23 01:03

Pac0