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?
When should we use classes and interfaces? If you want to create and pass a type-checked class object, you should use TypeScript classes. If you need to work without creating an object, an interface is best for you.
TypeScript vs JavaScript: HighlightsJavaScript is better suited for small-scale applications, while TypeScript is better for larger applications. TypeScript supports static typing but JavaScript does not. TypeScript supports interfaces but JavaScript does not. TypeScript features prototyping but JavaScript does not.
You can have typescript compile javascript files as well using 'allowJs' (in tsconfig. json). That way, you can reference typescript classes from your javascript.
TypeScript is an object-oriented programming language developed by Microsoft Corporation, whereas JavaScript is the programming language for the web. TypeScript is an open-source language to build large-scale web apps, whereas JavaScript is a server-side programming language that helps to develop interactive web pages.
Answering your questions:
@class
is a kind of annotation/comment that nothing as to do with the standard.
In ES5 (let's say "classic JavaScript") there are no classes, but there is a way to simulate their behaviour, also when TypeScript code is transpiled to ES5. That way to code "classes" (remember that they aren't there) is a bit harder compared to new specifications.
See answer 2 too. Also:
Since the modern JavaScript ECMAScript 6 specification (ES6), now JavaScript has classes. TypeScript is a kind of evolution of ES6. In ES6, it would be like this:
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
var newUser = new User('Rohit Bhatia', '[email protected]');
/** @class */
is just a commentIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With