มีวิธีการซ้อนคลาสใน TypeScript หรือไม่ เช่นฉันต้องการใช้มันเช่น:
var foo = new Foo();
var bar = new Foo.Bar();
มีวิธีการซ้อนคลาสใน 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();
นี่คือกรณีการใช้งานที่ซับซ้อนมากขึ้นโดยใช้การแสดงออกในชั้นเรียน
ช่วยให้ชั้นในสามารถเข้าถึงprivateสมาชิกของชั้นนอกได้
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());
ฉันไม่สามารถทำให้สิ่งนี้ทำงานกับคลาสที่ส่งออกโดยไม่ได้รับข้อผิดพลาดในการคอมไพล์ฉันใช้เนมสเปซแทน:
namespace MyNamespace {
export class Foo { }
}
namespace MyNamespace.Foo {
export class Bar { }
}
หากคุณอยู่ในบริบทของไฟล์การประกาศประเภทคุณสามารถทำได้โดยผสมคลาสและเนมสเปซ:
// 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();