TypeScriptのprotectedに相当するものは何ですか?
派生クラスでのみ使用されるように、基本クラスにいくつかのメンバー変数を追加する必要があります。
2014 年 11 月 12 日。TypeScript のバージョン 1.3 が利用可能になり、protected キーワードが含まれています。
2014 年 9 月 26 日。protected
キーワードが上陸しました。現在プレリリース中です。非常に新しいバージョンの TypeScript を使用している場合は、protected
キーワードを使用できるようになりました... 以下の回答は、古いバージョンの TypeScript に対するものです。楽しみ。
class A {
protected x: string = 'a';
}
class B extends A {
method() {
return this.x;
}
}
TypeScript にはprivate
- のみがあり、保護されていません。これは、コンパイル時のチェック中にのみ非公開であることを意味します。
アクセスしたい場合super.property
は、公開する必要があります。
class A {
// Setting this to private will cause class B to have a compile error
public x: string = 'a';
}
class B extends A {
method() {
return super.x;
}
}
次のアプローチはどうでしょうか。
interface MyType {
doit(): number;
}
class A implements MyType {
public num: number;
doit() {
return this.num;
}
}
class B extends A {
constructor(private times: number) {
super();
}
doit() {
return super.num * this.times;
}
}
num
変数はパブリックとして定義されているため、これは機能します。
var b = new B(4);
b.num;
ただし、インターフェイスで定義されていないため、次のようになります。
var b: MyType = new B(4);
b.num;
になりThe property 'num' does not exist on value of type 'MyType'
ます。このプレイグラウンド
で試すことができます。
インターフェイスのみをエクスポートしながらモジュールにラップすることもできます。その後、他のエクスポートされたメソッドからインスタンス (ファクトリ) を返すことができます。これにより、変数のパブリック スコープがモジュールに「含まれる」ようになります。
module MyModule {
export interface MyType {
doit(): number;
}
class A implements MyType {
public num: number;
doit() {
return this.num;
}
}
class B extends A {
constructor(private times: number) {
super();
}
doit() {
return super.num * this.times;
}
}
export function factory(value?: number): MyType {
return value != null ? new B(value) : new A();
}
}
var b: MyModule.MyType = MyModule.factory(4);
b.num; /// The property 'num' does not exist on value of type 'MyType'
この遊び場の修正版。
私はそれがあなたが求めたものと正確ではないことを知っていますが、それはかなり近いです.
少なくとも現時点 (バージョン 0.9) で保護されていることは仕様に記載されていません
http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf