将对象转换为某个类,将该类的函数添加到该对象

时间:2017-02-16 17:58:24

标签: typescript

假设我有以下课程:

class Person {

    name: string;
    age: number;
    country: string;

    canVote(): boolean {
        return (this.country === "SomeCountry" && this.age >= 16) || (this.country === "SomeOtherCountry" && this.age >= 18);
    }

}

在typescript中是否有任何方法可以将包含nameagecountry属性的对象转换为类Person的实例,我可以调用它canVote 1}},就像这样? (现在,这不会编译,因为缺少canVote

let person: Person = {
    name: "SomePerson",
    age: 42,
    country: "SomeCountry"
}

console.log(person.canVote());

我知道有参数属性允许我执行以下操作:

class Person {

    constructor(readonly name: string, readonly age: number, readonly country: string) {
    }

    canVote(): boolean {
        return (this.country === "SomeCountry" && this.age >= 16) || (this.country === "SomeOtherCountry" && this.age >= 18);
    }

}

let person = new Person("SomePerson", 42, "SomeCountry");

但是,我想如果属性数量增加或者我想要保留一个可选属性,那么很快就会变得不清楚。

1 个答案:

答案 0 :(得分:0)

您可以使用构造函数的接口并在构造函数中使用它。这样,它将始终保持结构清洁,如果您愿意,可以在以后轻松扩展属性。

interface ICharacter {
    name: string;
    age: number;
    country: string;
}

class Person {
    character: ICharacter;

    constructor(character: ICharacter) {
        this.character = character;
    }

    canVote(): boolean {
        return (this.character.country === "SomeCountry" && this.character.age >= 16)
            || (this.character.country === "SomeOtherCountry" && this.character.age >= 18);
    }
}

let character: ICharacter = {
    name: "SomePerson",
    age: 42,
    country: "SomeCountry"
};

let person: Person = new Person(character);
console.log(person.canVote());