在装饰器中扩展 class 会破坏静态 属性 继承

Extentending a class in decorator breaks static property inheritance

Codesandbox 文件 weird.spec.ts 中的测试失败(忽略 React 内容)。
要查看失败的测试,请单击右上角的 Show tests

我有一个 class 和一个用于验证的装饰器:

function Validate(original: any) {
    return (class extends original {
            constructor(...args: any[]) {
                super(...args);
                // some validation here,
                // throwing a custom error
            }
        }
    ) as any;
}

@Validate
export class Weird {
    public value: string;

    constructor(value: string) {
        this.value = value;
    }

    static thing = new Weird('thing');
}

我的问题(在失败的测试中可以看出)是

Weird.thing instanceof Weird // false

我也尝试过为此使用 getter,它按预期工作,但每次都会 return 一个新实例。我真正想要的是:

  1. 静态 属性 允许以 "enum" 方式使用 class
  2. Returns 同一个实例(初始化一次)
  3. 保持继承。
  4. 不是手动显式编码"cached static getter"。我同意编译器为我做这件事。

我需要调整什么来改变当前行为以匹配我想要的?

它是一个 known issue,在应用装饰器之前静态初始值设定项 运行,因此看到未装饰的 class。作为解决方法,您可以在 class 定义之后设置 Weird.thing

@Validate
class Weird {
    public value: string;

    constructor(value: string) {
        this.value = value;
    }

    static thing: Weird;
}
Weird.thing = new Weird('thing');