When null is multiplied by any number in Typescript, the result should be null, not 0

In C#, I encountered a situation:

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

Contrastingly, in TypeScript:

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

**How can I achieve null instead of 0 in TypeScript?

I'm looking for a generic solution rather than relying on ternary operators to check both properties for null and return null.

Are there any compiler options that need to be set in tsconfig.json?**

Answer №1

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:

  1. Easily transform all nulls into NaN.

  2. Give NaN as a result if any operand in an operation is NaN, without requiring changes in the computation code.

  3. 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.

  4. 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

Execute autofix to organize these imports using the simple-import-sort/imports plugin in TypeScript with ESLint

My code was being autofixed and cleaned up by Eslint, but then I decided to add two new eslint plugins: "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.26.0", https://github.com/lydell/es ...

Experiencing excessive memory usage when attempting to load a large JSON file in Firefox

We are in the process of developing a client-based application using HTML5 and indexedDB on Firefox 28. When large amounts of data are loaded to Firefox for the first time using AJAX requests in JSON format, each JSON response is approximately 2MB (gzipped ...

Navigating through objects within arrays within objects in Angular

I seem to be encountering some difficulty in displaying data from an API call on Mapbox. Only one marker is showing up on the map instead of the expected 10 markers. I suspect there might be an issue with my ng-repeat implementation, but I can't pinpo ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

Is there a javascript function that performs the reverse action of indexof()?

Is there a JavaScript function that is the opposite of indexOf()? In my code, when you press the button it will display 3 [from indexOf(".")]. However, I am looking for a function that is the opposite of indexOf(), which would show me 2 [decimal]. http: ...

Unable to update React state on a component that is unmounted while utilizing Redux

Utilizing Redux for managing a global Dialog component, I am passing the child components to the Dialog component through Redux actions. You can find a functional example in this codesandbox: https://codesandbox.io/s/suspicious-keldysh-uuolb?file=/src/App ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

What is the best way to create an interface that only allows keys to be a combination of values from a specific property found within each object of an array?

interface Filter { id: string; name: string; } type Filters = Filter[]; const filters = [{ id: 'f1', name: 'f1name'}, { id: 'f2', name: 'f2name'}] interface State { ... } const state = { f1: any, ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

Distinguishing Literal and Parameterized Routes in Angular 6

I've encountered a strange issue that I'm not sure how to handle. In my application, you can either view your public account or create a new one. The Account and CreateAccount modules are standalone and lazy loaded in the routes.ts file. export ...

Converting the AppDelegate.m file to AppDelegate.mm and updating the AppDelegate.h file during the transition from React Native 0.66.4 to 0.71.3

Original code in AppDelegate.h: #import <React/RCTBridgeDelegate.h> #import <UIKit/UIKit.h> #import <UserNotifications/UserNotifications.h> @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificat ...

Trouble with using the date pipe in Angular specifically for the KHMER language

<span>{{ value | date: 'E, dd/MM/yyyy':undefined:languageCode }}</span> I am facing a challenge where I need to identify the specific locale code for the KHMER language used in Cambodia. Despite trying various cod ...

Ways to share socket.io instance with other TypeScript modules

When it comes to exporting an io object obtained from initializing socket.io to my router module in typescript, I am unsure whether I should export the io object from the server.ts module or initialize socket.io in my router module. Are there any other rec ...

Import a file into a structure using c#

I am facing the challenge of reading a binary file that contains an unknown number of structs arranged one after another. Here is some Pseudo Code: struct: int64 timestamp, byte dataBlock1[600][16] byte dataBlock2[600][16] open = FileOpen(...) ...

The code functions properly when tested on a local server, but doesn't produce any results when

Currently, I am working on customizing a premade website and have been tasked with making a modification. The goal is to implement a confirmation box that appears when a button to delete a meeting task is clicked, rather than immediately deleting it. Afte ...

Determine the label's location in relation to the panel

I am facing an issue with a form that has a 'main' panel containing numerous labels. The panel is larger than the form and is scrollable (Autoscroll = true). My challenge is to obtain the position of these labels in relation to the top left corne ...

Avoid adding any empty entries to the list using jQuery

I have implemented a code to prevent any blank entries from being added to my list, and it seems to be working fine. However, I can't shake the feeling that there might be a better way to achieve this. Even though it functions correctly, it doesn&apos ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...