Javascript 您能在TypeScript中创建嵌套类吗?
有没有办法在TypeScript中嵌套类。例如,我想像这样使用它们:Javascript 您能在TypeScript中创建嵌套类吗?,javascript,typescript,Javascript,Typescript,有没有办法在TypeScript中嵌套类。例如,我想像这样使用它们: var foo = new Foo(); var bar = new Foo.Bar(); 从TypeScript 1.6开始,我们有类表达式() 这意味着您可以执行以下操作: class Foo { static Bar = class { } } // works! var foo = new Foo(); var bar = new Foo.Bar(); 我无法在没有收到编译错误的情况下使用导出类
var foo = new Foo();
var bar = new Foo.Bar();
从TypeScript 1.6开始,我们有类表达式() 这意味着您可以执行以下操作:
class Foo {
static Bar = class {
}
}
// works!
var foo = new Foo();
var bar = new Foo.Bar();
我无法在没有收到编译错误的情况下使用导出类,而是使用了:
下面是一个使用类表达式的更复杂的用例 它允许内部类访问外部类的
私有成员。
class classX {
private y: number = 0;
public getY(): number { return this.y; }
public utilities = new class {
constructor(public superThis: classX) {
}
public testSetOuterPrivate(target: number) {
this.superThis.y = target;
}
}(this);
}
const x1: classX = new classX();
alert(x1.getY());
x1.utilities.testSetOuterPrivate(4);
alert(x1.getY());
如果您在类型声明文件的上下文中,可以通过混合类和名称空间来实现这一点:
// foo.d.ts
declare class Foo {
constructor();
fooMethod(): any;
}
declare namespace Foo {
class Bar {
constructor();
barMethod(): any;
}
}
// ...elsewhere
const foo = new Foo();
const bar = new Foo.Bar();
对于较旧的typescript(此示例在typescript 1.6.3中不起作用:错误TS4028导出类的公共静态属性“Bar”具有或正在使用私有名称(匿名类)“.@Sergey我也遇到了同样的问题,所以根据我下面的回答开始使用名称空间。有没有办法在类内部创建接口?例如,如果我们想要,该条将是一个interface@LittaHervi-一个用例是从工厂方法返回外部接口的私有实现。另一个例子来自Java(和其他)是迭代器,需要对其包含类的成员变量进行特权访问,并通过作用域规则自动进行访问,但您永远不希望直接导出和实例化这些变量。@RyanCavanaugh是访问“内部”中的私有成员的能力类表达式一个bug?我在TypeScript团队中验证了这是正确的用法。它是否可以访问父上下文而不直接传递它?@shabunc not to my knowledgeidea如果您需要一个“true”(而不是“static”)内部类(作为对象模板),请像
()=>新类
相同。'Foo'仅指类型,但在此处用作命名空间。
// foo.d.ts
declare class Foo {
constructor();
fooMethod(): any;
}
declare namespace Foo {
class Bar {
constructor();
barMethod(): any;
}
}
// ...elsewhere
const foo = new Foo();
const bar = new Foo.Bar();