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());
好的,所以定义一个与朋友可访问的成员的接口,对吧? –
我喜欢你的最后一个例子,尽管声明类Bletch的语法似乎有点被强制。我发现唯一的缺点是Bletch似乎被VS Code IntelliSense标记为“匿名类”。 –
P.S.我对你的示例代码提出了一个小调整,摆脱了额外的私有属性。 –