48

TypeScriptのprotectedに相当するものは何ですか?

派生クラスでのみ使用されるように、基本クラスにいくつかのメンバー変数を追加する必要があります。

4

3 に答える 3

51

アップデート

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;
    }
}
于 2013-03-07T16:44:16.627 に答える
4

次のアプローチはどうでしょうか。

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'

この遊び場の修正版。

私はそれがあなたが求めたものと正確ではないことを知っていますが、それはかなり近いです.

于 2013-03-28T20:54:01.637 に答える
1

少なくとも現時点 (バージョン 0.9) で保護されていることは仕様に記載されていません

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

于 2013-06-23T19:54:19.613 に答える