Reason behind the zero result in your scenario
In TypeScript/JS/ES, when performing an arithmetic operation with a number and null
, the null
is automatically converted to a number, which results in it being converted to 0.
If you desire the "C# null-swallowing" behavior, then you need to explicitly specify it like this:
let c = x === null || y === null ? null : x * y;
The default behavior in Typescript is aligned with JavaScript/EcmaScript: any operation involving a number and null will coerce null into the number 0.
Are there any specific compiler options that need to be set in tsconfig.json?
As far as I know, there are no such options needed or should be included because the arithmetic operations function according to ES/JS rules, and TypeScript does not try to alter these rules towards what's used in C#.
I want to establish a generic method instead of using ternary operators and checking for both properties being null before returning null.
An alternative approach utilizing NaN / undefined
To simplify code structure and create a mechanism where certain special values can halt every operation (similar to how null
works in C#), you could consider using NaN
(Not a Number) instead of nulls.
This approach would:
Easily transform all nulls into NaN.
Give NaN as a result if any operand in an operation is NaN, without requiring changes in the computation code.
If necessary, NaNs can be converted back to nulls. Remember to use Math.IsNan()
to check for NaN, rather than comparing with === NaN
since the latter will always return false, even when comparing two NaNs.
Additionally, if one operand is undefined
, the outcome of an operation will also be NaN
. In this case, converting nulls to undefined may feel more natural from a C# perspective. This adjustment might also streamline serialization processes (e.g., using
Newtonsoft.Json.NullValueHandling.Ignore
).
This method may not directly apply to your situation, but it's beneficial to explore if you wish to reduce conditional statements in your code as mentioned earlier.