2016-03-19 4 views
5

TypeScriptを使用して、クラスとそのパブリックプロパティを定義できます。クラスに対して定義されたすべてのパブリックプロパティのリストを取得するにはどうすればよいですか。クラス/インタフェースのすべてのパブリックプロパティをリストしたい

class Car { 
    model: string; 
} 

let car:Car = new Car(); 
Object.keys(car) === []; 

車にはmodelのプロパティを送信する方法はありますか?

+2

これは既に回答済みです( 'hasOwnProperty'を使用しているかもしれません):https://stackoverflow.com/questions/35691858/typescript-hasownproperty-equivalentと' typeof'演算子https://developer.mozilla.org/en –

+1

実行時に 'public'と' private'のメンバーが同じように見えるので、あなたが記述したような公開APIを見つけることはできないと思います。 – Aaron

答えて

-3

更新の回答(また、私の答えは解決しない、プライベート/パブリック最終JSのクレーン変人の回答を参照してください):

class Vehicle { 
    axelcount: number; 
    doorcount: number; 

    constructor(axelcount: number, doorcount: number) { 
     this.axelcount = axelcount; 
     this.doorcount = doorcount; 
    } 

    getDoorCount(): number { 
     return this.doorcount; 
    } 
} 

class Trunk extends Vehicle { 
    make: string; 
    model: string; 

    constructor() { 
     super(6, 4); 
     this.make = undefined; // forces property to have a value 
    } 

    getMakeAndModel(): string { 
     return ""; 
    } 
} 

使用法:

let car:Trunk = new Trunk(); 
car.model = "F-150"; 

for (let key in car) { 
    if (car.hasOwnProperty(key) && typeof key !== 'function') { 
     console.log(key + " is a public property."); 
    } else { 
     console.log(key + " is not a public property."); 
    } 

} 

出力:

axelcount is a public property. 
doorcount is a public property. 
make is a public property. 
model is a public property. 
constructor is not a public property. 
getMakeAndModel is not a public property. 
getDoorCount is not a public property. 

以前の回答:

class Car { 
    model: string; 
} 

let car:Car = new Car(); 

for (let key in car) { 
    // only get properties for this class that are not functions 
    if (car.hasOwnProperty(key) && typeof key !== 'function') { 
    // do something 
    } 
} 
+5

このコードは間違っています。 'key'の型は決して' function 'になることはなく、 'hasOwnProperty'はプロトタイプから継承されたプロパティを除外します。宣言されているが未定義のプロパティは含まれず、プライベートプロパティまたは保護されたプロパティも除外されません。 –

2

上記のコメントですでに述べたように、パブリックメンバーとプライベートメンバーはJavascriptで同じように見えるので、それらを区別する方法はありません。しかし

var Car = (function() { 
    function Car(model, brand) { 
     this.model = model; 
     this.brand = brand; 
    } 
    return Car; 
}()); 
; 

あなたが見ることができるように、コンパイルされたJavaScriptバージョンでは、メンバーmodelbrandの間に違いは絶対にありません、イベント:たとえば、活字体のコード次

class Car { 
    public model: string; 
    private brand: string; 

    public constructor(model:string , brand: string){ 
     this.model = model; 
     this.brand = brand; 
    } 
}; 

がにコンパイルされますそのうちの1つはプライベートで、もう1つは公開されています。

いくつかの命名規則(たとえば、public_memberおよび__private_member)を使用して、プライベートメンバーとパブリックメンバーを区別することができます。

関連する問題