Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes!

While learning TypeScript, I created a simple code snippet like this:

class User {
  name: string;
  email: string;

  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
}

let newUser = new User("Rohit Bhatia", "example@email.com");

and then I was presented with this equivalent code:

var User = /** @class */ (function () {
    function User(name, email) {
        this.name = name;
        this.email = email;
    }
    return User;
}());
var newUser = new User("Rohit Bhatia", "example@email.com");

Now, I have a few questions:

  1. what does @class (or @ in general in JavaScript) mean?

    var User = /** @class */ (function () {

  2. are classes present in JavaScript as well? If so, why doesn't TypeScript transpile them into JavaScript classes?

  3. In TypeScript classes, we can define properties like this:

    class User { name: string; email: string;

But can we do the same thing in plain JavaScript? Is there a difference between JavaScript classes and TypeScript classes?

Answer №1

Responding to your inquiries:

  1. The @class tag serves as an annotation or comment that is unrelated to the standard.

  2. Before ES6 (commonly known as "classic JavaScript"), there were no classes. However, there was a workaround to mimic their functionality, even when TypeScript was transpiled to ES5. This method of creating "classes" (not actual classes) is more complex in comparison to newer standards.

  3. Refer to answer 2 as well.

With the introduction of ECMAScript 6 (ES6), JavaScript now supports classes. TypeScript can be seen as a progression from ES6. In ES6, the syntax would be as follows:

class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

var newUser = new User('Rohit Bhatia', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b3229341b3c363a323775383436">[email protected]</a>');

Answer №2

  1. /** @class */ is simply a comment
  2. By default, TypeScript transpiles to ES5, allowing the code to run on older browsers like IE11. However, setting ES6 as the target will result in the use of JS classes.
  3. In ES5, classes are written using a constructor function, but the outcome is the same as using ES6 classes.

Answer №3

I am providing a response to address the third query.

  1. According to the ECMAScript standard, anything between /* and */ is considered a comment. However, it is conceivable that the TypeScript transpiler or debugger may utilize these annotations for additional purposes.
  2. As noted in previous responses, TypeScript typically transpiles to ECMAScript 5 (ES5) by default in order to enhance compatibility with older browsers. This approach also allows for a class-like structure in ES5.
  3. While ES6 classes bear resemblance to TypeScript classes, TypeScript introduces public/protected/private modifiers that are absent in ES6 classes. Additionally, TypeScript offers benefits such as stronger typing, which can lead to improved autocomplete features in certain editors (such as Visual Studio Code, depending on the specific editor).

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

I am encountering difficulty in printing multiple documents from FireStore

I am facing an issue where I can successfully retrieve and print all documents from a Firestore collection one by one using console.log(). However, when attempting to display these documents on the screen, only the most recent document is showing up. Here ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Invalid web address entered

While attempting to incorporate a functionality that opens a new window to a specific link when clicking an icon, I encountered an issue where the click action redirects to the wrong URL. Instead of directing to the URL specified in its href attribute, it ...

Unable to fulfill the pledge

I'm struggling to receive the promise from the backend after making a get request. Can anyone help me figure out what I might be doing wrong? makeLoginCall(_username: string, _password: string) { let promise = new Promise((resolve, reject) => ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Leveraging Global Variables in TypeScript with Node Express

Having issues using global variables in node express when working with typescript. Specifically, trying to use the same global array variable tokenList:tokList across multiple modules and middleware, but haven't been successful so far. Any suggestions ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

Update to using res.get() instead of res.getHeader()

Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...

Add data to a DataTable without the need to manually refresh the page

I am looking to dynamically append a DataTable on my webpage. The goal is to have a form that users can fill out multiple times and each time they submit their inputs, the results will be added to the DataTable for display. <table id="table" class="di ...

Jquery Fails to Execute When Clicking on Radio Button

Whenever a user selects a radio button, I want to display an alert box. I have already written the jQuery code to achieve this. Here is my implementation: <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></ ...

Troubleshooting: Unable to delete data using $http in AngularJS

When using the $http service in Angular JS to call an API for deleting a message, I am receiving a successful response but the value is not actually being deleted. Interestingly, when I directly access the same API in my browser, the message gets deleted s ...

Using JavaScript variables in a Jinja array

I encountered a frustrating issue that has been causing me some trouble. In my project setup, data is being transferred from Python to the frontend using Jinja in the form of a 2D list. My goal is to loop through this array using a for loop, but I'm ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...