2017-02-16 4 views
0

私は以下のクラスがあるとします。いくつかのクラスへのキャストオブジェクト、

class Person { 

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

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

} 

があることをnameagecountry属性を含むオブジェクトをキャストするtypescriptですのいずれかの方法はあります私がcanVoteと呼ぶことができるクラスPersonのインスタンスはそうですか?

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"); 

しかし、私はこれが不明確になるだろうと想像:

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

console.log(person.canVote()); 

を(canVoteが欠落しているため、今のところ、これはコンパイルされません)私は、私は次の操作を実行できるようになるパラメータのプロパティがあります知っていますプロパティの数が増えたり、オプションのプロパティを設定しないままにしたい場合はかなり高速です。

答えて

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()); 
関連する問題