Converting JavaScript code containing ?? to TypeScript is not feasible

I've encountered a dilemma while attempting to convert several JS files with double question marks to TypeScript using tsc.

Unfortunately, the tsc compiler does not recognize ??.

For example: this.x = typeof params.x == "string" ? this._processStringParam(params.x, "x") : params.x ?? 0;

This results in the error message: imageElement.js:70:96 - error TS1109: Expression expected. this.x = typeof params.x == "string" ? this._processStringParam(params.x, "x") : params.x ?? 0;

I am puzzled by the fact that the presence of double question marks is the main motivation for converting to TS. So, why fix it in JS before running through tsc?

What is the best approach to convert these js files to TypeScript then?

The tsconfig.json file appears as follows:

{
    "compilerOptions": {
        "checkJs": false,
        "module": "commonjs",
        "target": "ES5",
        "allowJs": true,
        "rootDir": "./",
        "baseUrl": "./",
        "outDir": "./build",
        "noStrictGenericChecks": true,
        "skipLibCheck": true,
        "strictFunctionTypes": false,
        "lib": [
            "es2015",
            "dom"
        ]
    },
    "exclude": [
        "./build/**"
    ]
}

Answer №1

Experiment with it by modifying the destination to "ES6"

The reason for this is due to the introduction of the ?? or nullish coalescing operator in versions after ES2020

Answer №2

Here is a suggested configuration:

    "compilerOptions": {
    /* Language and Settings */
    "target": "ES5",                                     /* Define the JavaScript language version for output files and include compatible library declarations. */

    /* Modules */
    "module": "commonjs",                                /* Specify the module code generated. */
    "outDir": "dist",                                   /* Set an output directory for emitted files. */
    "esModuleInterop": true,                             /* Output additional JavaScript to simplify importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure correct case usage in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking of all .d.ts files. */
  }

TypeScript code example:

console.log('coalescing nullish with undefined: ', undefined ?? 'compare with undefined');
console.log('coalescing nullish with null: ', null ?? 'compare with null');
console.log('coalescing nullish with valid data: ', 'with data' ?? 'compare with null or undefined');

Transpiled JavaScript code:

console.log('coalescing nullish with undefined: ', undefined !== null && undefined !== void 0 ? undefined : 'compare with undefined');
console.log('coalescing nullish with null: ', null !== null && null !== void 0 ? null : 'compare with null');
console.log('coalescing nullish with valid data: ', 'with data' !== null && 'with data' !== void 0 ? 'with data' : 'compare with null or undefined');

Output on console:

coalescing nullish with undefined:  compare with undefined
coalescing nullish with null:  compare with null
coalescing nullish with valid data:  with data

This JavaScript code maintains ES5 compatibility.

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

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

Finding the current week using date information from an array of objects in JavaScript

I have an array of objects with a date key, and I am trying to filter out the objects that fall within the current week. How can I achieve this and get the objects from the current week? I attempted to use the filter method, but I believe I need to forma ...

angular and node: troubleshooting the $http.get error

I have encountered an issue with the $http.get instruction. Without it on the main page, I receive a result of "random 46" which is correct. However, when I include $http.get, I get a result of "random {{ number }}". How can this problem be resolved? -se ...

Turn off the ability to debug XHR requests in the developer tools of all web browsers for my website

Is there a method to prevent website users from viewing the communication between my web application and the server via ajax requests? Is there a way to achieve this on my website using code? I want to make sure that the XHR, Ajax calls, and responses ca ...

When a user right-clicks on certain words, the menu opens using JavaScript

Looking to implement a custom context menu that opens when specific words are right-clicked by the user in JavaScript. I have been searching for a solution for quite some time now. The word should be recognized based on an array of specific words. Can some ...

What is the alternative method for converting an API stream into a .csv file without relying on FileSaver or createObjectURL()?

These are the only two methods currently available. An issue with createObjectURL() is that it is deprecated and cannot be called in Chrome anymore. Using FileSaver may feel like adding unnecessary complexity to your project when it should be a simple ta ...

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

Integrate a loading screen on the website

Check out the awesome animation I created! Can this be used as a preloader on my website? Should I stick to creating a simple .gif or opt for a CSS animation instead? If it’s feasible, how do I go about integrating it into my site? Most tutorials suggest ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py ...

A step-by-step guide for invoking a JSON-based API

I'm currently facing an issue with calling a JSON-based authentication API. The API requires two parameters, username and password, to be passed in JSON format. What could be the mistake in my approach? Below is the snippet of my current test code: ...

Tips for maintaining the selection when switching pages with smart-table?

I have implemented smart-table in my project to allow users to select records from different pages and view them in a preview section. However, I am facing an issue where the selection made on the first page does not persist when navigating back to it aft ...

Prevent child div from resizing along with parent div during a resize event by utilizing the .resizable()

Check out this example here I am able to resize the div using jQuery, but I don't want the #spacer to have a fixed width at first because the content of the could vary in size. Even if I remove: width:100px; and try setting it to a percentage or ...

What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, ...

The Vue EventBus does not support passing object attributes

Looking for assistance with integrating two Vue single page components. The 'Searchbar' component features a dialog box where users input data. This data is required in the 'ResultList' component for further processing. To achieve this ...

Are the Angular tests passing even before the asynchronous call has finished?

When running the following Angular (4) test for a service, it appears to pass before the Observable returns and hits the expect statement. it('should enter the assertion', inject( [ MockBackend, CellService ], ( backend: MockB ...

Automate brush control and transmit pertinent data through coding

Extending on the query from yesterday's thread, I am working towards implementing multiple brushes. While my current brute force method is functional, I require additional functionality to programmatically manage each of these newly created brushes. ...

A variant of setTimeout designed specifically for family members

I am currently working on a program that involves creating a "health" variable which decreases by random amounts at random intervals. This means that a player may encounter scenarios like the following: 5 seconds Lose 20 health 3 more seconds Lose 25 healt ...

Obtain the image and store it in the designated storage location

I need help with a web page that features a profile viewing section. I have an empty image placeholder and when clicked, it prompts the user to browse for an image. However, I am struggling with saving the selected image into storage. Below is my code snip ...

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...