'JavaScript classes vs TypeScript classes
I am new to TypeScript and JavaScript classes!
I was learning TypeScript where I created something as simple as this
class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}
let newUser = new User("Rohit Bhatia", "[email protected]");
and this was given to me as equivalence
var User = /** @class */ (function () {
function User(name, email) {
this.name = name;
this.email = email;
}
return User;
}());
var newUser = new User("Rohit Bhatia", "[email protected]");
Now, I have three questions
what is
@class(or@in general in JavaScript)?var User = /** @class */ (function () {classes are in JavaScript as well? So why doesn't TypeScript transform them into JS classes?
in TS class we can do something like this
class User { name: string; email: string;
but can't we do something like this in JavaScript? Or what is the difference between JS classes and TS classes?
Solution 1:[1]
/** @class */is just a comment- TypeScript's default target is ES5 so it transpiles to JS code that can execute on browsers as old as IE11. If you set ES6 as target, you'll notice that JS classes will be used
- ES5 way for writing classes is to use a function as a constructor, but the result when executing the code is exactly the same as ES6 classes
Solution 2:[2]
I'm answering to complete the third question.
- In ECMAScript standard, what is between
/*and*/is just a comment, but it's possible that TypeScript transpiler or debugger use this annotations for something more. - As said in the other answers, by default TypeScript transpile for ECMAScript 5 (ES5), for better compatibility with old browsers, and that it's a way to do something like class in ES5.
- The ES6 classes are similar to TypeScript classes, but TypeScript also has public/protected/private modifiers, that there aren't in ES6 classes. Also, in TypeScript you will have advantages by the stronger typing, which includes even better autocomplete in some editors (like Visual Studio Code, of course it depends of the editor).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paolo |
| Solution 2 | Paolo |
