0
私は以下のクラスがあるとします。いくつかのクラスへのキャストオブジェクト、
class Person {
name: string;
age: number;
country: string;
canVote(): boolean {
return (this.country === "SomeCountry" && this.age >= 16) || (this.country === "SomeOtherCountry" && this.age >= 18);
}
}
があることをname
、age
とcountry
属性を含むオブジェクトをキャストする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
が欠落しているため、今のところ、これはコンパイルされません)私は、私は次の操作を実行できるようになるパラメータのプロパティがあります知っていますプロパティの数が増えたり、オプションのプロパティを設定しないままにしたい場合はかなり高速です。