2013-03-07 20 views
45

什麼是保護TypeScript什麼是在TypeScript中保護的等效物?

我需要在基類中添加一些成員變量,僅用於派生類

+0

您可以投票了這個CodePlex上的問題提到:http://typescript.codeplex.com/workitem/125 – 2013-03-07 18:28:12

+1

我已經更新了我的答案,以反映「protected」已登陸:https://github.com/Microsoft/TypeScript/pull/688 – Fenton 2014-09-26 07:01:46

回答

48

更新

2014年11月12日。版本1.3的TypeScript可用幷包含受保護的關鍵字。

2014年9月26日。protected關鍵字已降落。目前它是預發佈的。如果您使用的是TypeScript的新版本,則現在可以使用protected關鍵字...以下答案適用於舊版本的TypeScript。請享用。

View the release notes for the protected keyword

class A { 
    protected x: string = 'a'; 
} 

class B extends A { 
    method() { 
     return this.x; 
    } 
} 

老回答

打字稿只有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; 
    } 
} 
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'
您可以在此playground中試用。

您也可以將其包裝在模塊中,而只導出接口,然後從其他導出的方法中返回實例(工廠),這樣變量的公共範圍將被「包含」在模塊中。

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' 

修改版本在playground

我知道這不是你要求的,但它非常接近。

相關問題