You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在外部类中访问作为表达式的内部类的静态成员?

如何在外部类中使用嵌套非静态内部类的成员?

这是「如何将嵌套非静态类型用作构造函数参数类型」问题的跟进。

现有类型定义已准备完毕,但在外部类代码中访问内部类成员时遇到编译错误。示例代码如下:

class JavaObject {
}

class Enum<T> {
  public constructor(public name: string, public value: number) {}
}

export class CodePointBuffer extends JavaObject {
    public Type = (($outer) => {
        return class Type extends Enum<Type> {
            public static readonly BYTE: Type = new class extends Type {
            }(`BYTE`, 0);
            public static readonly CHAR: Type = new class extends Type {
            }(`CHAR`, 1);
            public static readonly INT: Type = new class extends Type {
            }(`INT`, 2);
        };
    })(this);

    private readonly type: InstanceType<typeof this.Type>;

    public constructor(type: CodePointBuffer.Type) {
        super();
        this.type = type;
    }

    public static withBytes = (): CodePointBuffer => {
        return new CodePointBuffer(this.Type.BYTE);
    };
}

export namespace CodePointBuffer {
    export type Type = InstanceType<CodePointBuffer["Type"]>;
}

当前问题:CodePointBuffer的type成员初始化无法通过编译,CodePointBuffer.Type.BYTE不被识别,尝试CodePointBuffer["Type"].BYTE、this.Type.BYTE等写法均无效。

问题根源

当前将Type定义为实例属性,意味着每个CodePointBuffer实例都会拥有独立的Type类副本,而静态方法withBytes中的this指向类本身,无法访问实例属性。同时内部类的静态成员定义方式存在冗余,导致类型推导异常。

解决方案

将Type改为静态嵌套类,确保它属于CodePointBuffer类而非单个实例,同时简化内部类静态成员的定义:

class JavaObject {
}

class Enum<T> {
  public constructor(public name: string, public value: number) {}
}

export class CodePointBuffer extends JavaObject {
    // 将Type改为静态类,无需IIFE绑定外部this
    public static Type = class Type extends Enum<Type> {
        // 直接实例化当前Type类,无需匿名继承
        public static readonly BYTE: Type = new Type(`BYTE`, 0);
        public static readonly CHAR: Type = new Type(`CHAR`, 1);
        public static readonly INT: Type = new Type(`INT`, 2);
    };

    private readonly type: CodePointBuffer.Type;

    public constructor(type: CodePointBuffer.Type) {
        super();
        this.type = type;
    }

    public static withBytes = (): CodePointBuffer => {
        // 静态方法中通过类本身访问静态嵌套类的成员
        return new CodePointBuffer(CodePointBuffer.Type.BYTE);
    };
}

export namespace CodePointBuffer {
    export type Type = InstanceType<typeof CodePointBuffer.Type>;
}

关键修改点

  • 将Type从实例属性改为static静态属性,使其属于CodePointBuffer类而非单个实例。
  • 简化内部类静态成员的创建方式,直接使用new Type(...)替代匿名类继承,避免类型混淆。
  • 调整命名空间中的Type类型定义,直接基于静态类的类型推导。
  • 静态方法withBytes中通过CodePointBuffer.Type.BYTE访问静态成员,而非this.Type。

修改后代码可正常编译,且能正确访问内部类的静态成员。

内容的提问来源于stack exchange,提问作者Mike Lischke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:30:40