Ueli Kramer Ueli Kramer - 1 month ago 6
TypeScript Question

Typescript object casting not working

I got an HTTP API.
I am loading a set of objects as a json.

I want to cast to a Typescript object, but with the keyword "as" it is not working and even not with < Type > in front of the object.

r.forEach(entry => {
entry.creationDate = new Date(entry.creationDate.date);
entry.creator = <User>entry.creator;
return entry;
});


The console.log directly after entry.creator casting outputs a normal "Object".

Can someone give me an advice?

Answer

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.