如何与打字稿中的所有成员一起演员?

时间:2017-04-24 19:48:41

标签: javascript typescript

我有一个类似的Typescript类:

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; 
    }

然后在其他课程中我尝试施放另一个类:

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

之后person对象&#34;失去&#34;它的方法。我怎样才能将CreatePerson转换为保留所有方法?

1 个答案:

答案 0 :(得分:2)

如果我的猜测是正确的那么otherObject是这样的:

{
    name: "name",
    surname: "surname"
}

如果是这种情况,那么你不能只是投射它并获得CreatePerson的实例。
因为打字稿使用structural typing,所以以下工作:

let p1: CreatePerson = new CreatePerson();
let p2: CreatePerson = {
    name: "name",
    surname: "surname"
}

但是p2不是CreatePerson的实例,它只是共享相同的结构,但缺少方法。

与投射相同的是,如果你有一个具有相同结构的对象,并且你将它投射到CreatePerson,你仍然无法获得CreatePerson的实例。
你需要这样做:

var otherObject = { ... }
var person = new CreatePerson(otherObject);