How can I avoid transpiling in TypeScript when setting ESNext as the target in tsconfig.json?

I came across a similar question that I thought would be helpful: How to maintain ES6 syntax when transpiling with Typescript, but unfortunately, it didn't solve my issue... It's slightly different.

When running yarn tsc --project tsconfig.json on the file:

// ./index.tsx

class Person {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }

  _run = () => {
    console.log('I\'m running!')
  }
}
let person = new Person('John Doe');
console.log(person.name);

The transpiled code looked like this:

// ./index.js

class Person {
    constructor(name) {
        this._run = () => {
            console.log('I\'m running!');
        };
        this.name = name;
    }
}
let person = new Person('John Doe');
console.log(person.name);

Now, how can I achieve the same code as the input without any additional postprocessing steps?

This is my tsconfig.json configuration:

{
  "compilerOptions": {
    "baseUrl": ".",
    "alwaysStrict": true,
    "noImplicitAny": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "allowJs": true,
    "checkJs": false,
    "module": "ESNext",
    "target": "ESNext", 
    "jsx": "react",
    "moduleResolution": "node",
    "types": ["node"],
    "lib": ["dom", "es6", "es2017", "es2018", "es2019", "es2020","esnext"]
  },
  "linebreak-style": [true, "LF"],
  "typeAcquisition": {
    "enable": true
  },
  "include": [
    "**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts",
    "**/*.test.tsx",
    "dist"
  ]
}

Answer №1

By activating the useDefineForClassFields setting in your tsconfig.json file, you can produce JavaScript code that closely resembles your TypeScript code:

{
  "compilerOptions": {
    "useDefineForClassFields": true
  }
}

Let's take an example:

// ./index.tsx

class Person {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }

  _run = () => {
    console.log('I\'m running!')
  }
}
let person = new Person('John Doe');
console.log(person.name);

This will be converted to:

// index.js
"use strict";
class Person {
    name;
    constructor(name) {
        this.name = name;
    }
    _run = () => {
        console.log('I\'m running!');
    };
}
let person = new Person('John Doe');
console.log(person.name);

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

Tips for accessing a value in a multidimensional json array without the key in JavaScript/jQuery?

I'm working with a JSON file that contains a multidimensional array. The array consists of city data at the first level and temperature data at the second level. I'm facing difficulties in dynamically extracting values from the second level. I a ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

When using AngularJS $http to send an object as a JSON key to a Spring controller, the returned value

I am attempting to transmit a json object from javascript to the Spring controller. My method of choice is using angularJs $http post for this. The issue arises when I send the key as object, with the lastName showing up as null. Strangely, if I send the s ...

Creating a clickable color-changing grid: A step-by-step guide

In a grid of size 12 by 12, each corner will be clickable, selecting a 6x3 cell area starting from the corner. The selected cells will change color upon clicking any of the 4 corners. After selecting one corner, the remaining cells (126 cells) will be che ...

Discovering the specific object ID that triggered an event in JavaScript

I am developing a webpage that includes JavaScript functionality. There is a specific function in the Javascript code which gets triggered by two different elements when clicked: 1. When a checkbox is clicked: $('#chkShowAll').click( functi ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

Expanding Images Using HTML and CSS

I am currently working on a memory card game using HTML, CSS, and JS as part of my practice. You can check out what I have accomplished so far right here: . Upon inspection, you may notice that the images of the question mark and the flipped card are sligh ...

Evaluating Angular directive scopes through function binding (&)

Currently, we are encountering some unusual behavior regarding the binding of a function to a directive scope. Check out an example on JSBin. Here's the scenario - we have a directive with a scope object structured like this: scope: { fn: '& ...

Using jQuery's slideToggle feature to hide content when clicked again or when a different button is

I have a challenge with creating toggle buttons that require specific functions: 1) Display content on the first click (this is working) 2) Conceal content when another button is clicked (this is also working) 3) Hide content on the second click (this i ...

The Vue ChartJS fails to display properly after the page is refreshed

Although this issue may appear to be a common one, some of the suggested solutions are outdated or no longer functional. My objective is to ensure that the chart remains responsive even after the page reloads. I attempted to implement the solution provided ...

Sharing an array between two sibling components

Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located wit ...

Verifying the execute boolean status or utilizing try/catch with PDO

Apologies for the subpar title. My project heavily relies on AJAX, with most responses returning either 'error' or 'success' messages in an array. In my Javascript code, I display these messages in a custom notification bar. I'm u ...

Custom directive with nested objects within a scope object

What is preventing me from having a binding in a nested object within my scope object, as demonstrated here: app.directive('myDirective', function() { return { scope: { dropdown: { option: '=selectedO ...

Determining Field of View (FOV) for a perspective camera in ThreeJS following a browser window resize

After changing the size of the browser window, I'm trying to determine the correct Three.JS camera FOV. I have looked at several related questions, but haven't found a solution yet: How to calculate fov for the Perspective camera in three js? C ...

Using asynchronous method calls to create arrays in ES6

In my current task, I am working on completing the following method: collectAllResults: function (callback) { this.getTotalCount((count) => { // the count typically is 5 let results = [] for (var i = 0; i < count; i++) { th ...

Creating a conditional npm script that depends on the output of another: a step-by-step guide

I've encountered this problem before while setting up npm scripts, and I haven't been able to find a solution yet. I'm hoping to make the solution compatible with both Mac and Windows environments. I'm working on splitting up the logic ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...

Is the type check being disregarded within the loop?

I encountered this issue while working with a React component: if (props.someArray){ // I need to typecheck because someArray is of type 'things[] | undefined' props.someArray.forEach((element, i) => { someFunction(i, elem ...

Controlling the HTML5 dialog element within a React application

Struggling to implement a basic configuration dialog with a close icon in the top-right corner using React. In other frameworks, it's easy to show/hide a dialog with .showModal()/close(), but manipulating the DOM directly in React is not recommended. ...