As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts
:
class Monster {
constructor(name, initialPosition) {
this.name = name;
this.initialPosition = initialPosition;
}
}
I had an assumption that we can dynamically add properties to the Monster
class just like in JavaScript. So using this.name
and this.initialPosition
should be valid. However, upon compiling the code, I encountered the following errors:
app1.ts(3,14): error TS2339: Property 'name' does not exist on type 'Monster'.
app1.ts(4,14): error TS2339: Property 'initialPosition' does not exist on type ' Monster'.
Initially, I assumed that adding properties dynamically might not be allowed (unlike in ES6 where it's possible), but when I reviewed the generated JavaScript code after the compilation error, it surprised me. The JS code created was as follows:
var Monster = /** @class */ (function () {
function Monster(name, initialPosition) {
this.name = name;
this.initialPosition = initialPosition;
}
return Monster;
}());
This whole process has left me a bit puzzled. Why did it generate JS after the compilation error? What exactly is happening behind the scenes?