2016-08-15 44 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.我对你的示例代码提出了一个小调整,摆脱了额外的私有属性。 –