I I've struggled with similar problems, and in my opinion this is a defect in typescript. When you are doing the cast as you did. Or a sample code 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();
You will notice that doConsole won't be a function in the casted object. That's the generated JS to this:
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 doesn't uses the prototype function you prepared by the class when doing the cast.
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 are using the prototype function, as you can see by 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 what I'm saying is that I agree with you that it should works like you did, but the transpiler doesn't use the prototyped function, so it won't work.
I hope this helps you.