I have encountered similar issues in the past, and in my perspective, this is a flaw in typescript. When performing the cast as demonstrated or with code like the example below:
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 may observe that the doConsole function will not be accessible in the casted object. This is how the resulting JS code looks after compilation:
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();
It becomes evident that the prototype function from the class is not utilized when casting.
In my experience, a workaround would involve something along these lines:
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 approach ensures that the proper prototype function is employed, as seen in the compiled JS code:
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();
In essence, my standpoint aligns with yours - it should function as intended, but due to the limitation of the transpiler, it doesn't utilize the prototyped function properly.
I trust this explanation aids you in understanding the issue better.