你能在 TypeScript 中创建嵌套类吗?

2022-08-30 04:40:13

有没有办法在TypeScript中嵌套类。例如,我想像这样使用它们:

var foo = new Foo();
var bar = new Foo.Bar();

答案 1

在现代TypeScript中,我们有类表达式,可用于创建嵌套类。例如,您可以执行以下操作:

class Foo {
    static Bar = class {
        
    }
}

// works!
var foo = new Foo();
var bar = new Foo.Bar();

答案 2

下面是一个使用类表达式的更复杂的用例。

它允许内部类访问外部类的成员。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());

密码笔