Q:

How to cast with all members in typescript?

I have a Typescript class like:
export class CreatePerson { 
    name: string; 
    surname: string; 
    constructor(data?: any) {
        if (data !== undefined) {
            this.name = data["name"] !== undefined ? data["name"] : null;
            this.surname = data["surname"] !== undefined ? data["surname"] : null;
        }
    }

    static fromJS(data: any): CreatePerson {
        return new CreatePerson(data);
    }

    toJS(data?: any) {
        data = data === undefined ? {} : data;
        data["name"] = this.name !== undefined ? this.name : null;
        data["surname"] = this.surname!== undefined ? this.surname: null;
        return data; 
    }

then in other class i try to cast another class:
var person = new CreatePerson();
var otherObject // this object contains the 'name' and 'surname' properties;    

this.person = <CreatePerson> otherObject;

this.person.name //works as expected
this.person.surname // works as expected
this.person.toJS() // error saying that is not a function here

after that the person object "looses" its methods. How can i cast to CreatePerson keeping all the methods?

A:

If my guess is correct then otherObject is something like this:
{
    name: "name",
    surname: "surname"
}

If that's the case then you cannot just cast this and get an instance of CreatePerson.
Because typescript uses structural typing then the following works:
let p1: CreatePerson = new CreatePerson();
let p2: CreatePerson = {
    name: "name",
    surname: "surname"
}

But p2 is not an instance of CreatePerson, it just shared the same structure, but the methods are missing.
Same thing with casting, if you have an object with the same strucutre and you cast it to CreatePerson you still won't get an instance of CreatePerson.
You'll need to do this:
var otherObject = { ... }
var person = new CreatePerson(otherObject);

