2016-08-15 88 views
0

發佈的關於typecript和嵌套類的過去的答案建議使用該語言的聲明合併功能。我曾與下面的例子,它執行按預期嘗試這樣做,但會產生一個編譯器消息:Typescript:模擬嵌套類+私人成員訪問

foo.ts(9,37): error TS2341: Property '_bar' is private and only accessible 
       within class 'Foo'. 

...因爲寫這似乎很奇怪,類Bletch 美孚的成員。

有沒有最佳實踐方法來抑制有關訪問外部類的私有成員的錯誤?(我知道我可以(this._foo as any)取代this._foo,但是看起來應該有更多更優雅的方式......)

例子:

export class Foo { 
    constructor(private _bar: number){} 
    //... 
} 

export module Foo { 
    export class Bletch { 
     constructor(private _foo: Foo) {} 
     barf(): number { return this._foo._bar; } 
    } 
} 

let a = new Foo(57); 
let b = new Foo.Bletch(a) 

console.log(b.barf()); 

回答

1

作爲一個類的成員不允許你訪問它的私有成員/方法,但通常是內部類可以。
在這種情況下,雖然你不是真的有一個內部類,你只需要添加類Bletch作爲Foo類的屬性,很容易在編譯JS看到:

var Foo = (function() { 
    function Foo(_bar) { 
     this._bar = _bar; 
    } 
    return Foo; 
}()); 
var Foo; 
(function (Foo) { 
    var Bletch = (function() { 
     function Bletch(_foo) { 
      this._foo = _foo; 
     } 
     Bletch.prototype.barf = function() { return this._foo._bar; }; 
     return Bletch; 
    }()); 
    Foo.Bletch = Bletch; 
})(Foo || (Foo = {})); 

你可以解決這個問題做這樣的事情:

module Foo { 
    interface Instance { 
     _bar: number; 
    } 

    export class Bletch { 
     private _foo: Instance; 

     constructor(foo: Instance | Foo) { 
      this._foo = foo as Instance; 
     } 

     barf(): number { return this._foo._bar; } 
    } 
} 

code in playground

您也可以選擇定義 「內部類」 的另一種方式:

interface Instance { 
    _bar: number; 
} 

class Foo { 
    constructor(private _bar: number) {} 

    static Bletch = class { 
     private _foo: Instance; 

     constructor(foo: Instance | Foo) { 
      this._foo = foo as Instance; 
     } 

     barf(): number { return this._foo._bar; } 
    } 
} 

code in playground

這看起來更像是它是如何完成的,通常,這是一個有點短。

+0

好的,所以定義一個與朋友可訪問的成員的接口,對吧? –

+0

我喜歡你的最後一個例子,儘管聲明類Bletch的語法似乎有點被強制。我發現唯一的缺點是Bletch似乎被VS Code IntelliSense標記爲「匿名類」。 –

+0

P.S.我對你的示例代碼提出了一個小調整,擺脫了額外的私有屬性。 –