I struggled with similar problems, and, in my opinion, this is a defect in typescript. When you do actors, so do you. Or an example code:
class User { name: string; doConsole(): void { console.log(`Name: ${this.name}`); } } let userObj = { name: 'jose' }; let user = new User(); Object.assign(user, userObj); user.doConsole();
You will notice that doConsole will not be a function in a cast object. This is the generated JS:
var User = (function () { function User(name) { this.name = name; } User.prototype.doConsole = function () { console.log("Name: " + this.name); }; return User; }()); var userObj = { name: 'jose' }; var user = userObj; user.doConsole();
As you can see, it does not use the prototype function that you prepared the class when performing the translation. My alternative was to do something like this:
class User { name: string; doConsole(): void { console.log(`Name: ${this.name}`); } } let userObj = { name: 'jose' }; let user = new User(); Object.assign(user, userObj); user.doConsole();
This ensures that you use the prototype function, as you can see the generated JS:
var User = (function () { function User() { } User.prototype.doConsole = function () { console.log("Name: " + this.name); }; return User; }()); var userObj = { name: 'jose' }; var user = new User(); Object.assign(user, userObj); user.doConsole();
So basically, I say that I agree with you that it should work the way you do, but the transpiler does not use the prototyped function, so it will not work.
Hope this helps you.
source share