从构造函数访问静态成员

时间:2019-06-10 12:34:29

标签: typescript types constructor static

我在从类构造函数的实例访问静态成员时遇到问题。该代码有效,但是类型信息错误。

var ctor: { new (...args: any[]): Foo } = undefined as any;

function decorator() {
    return function <T extends { new (...args: any[]): Foo }>(constructor: T) {
        ctor = constructor;
        return constructor;
    }
}

@decorator()
class Foo {
    static Func = () => console.log("Hi");
}

Foo.Func();
ctor.Func();
Foo.prototype.constructor.Func();

在上面的示例中,调用Foo.Func是可以的。第二个电话告诉我没有Func成员。第三个选项应该基本上与第二个选项相同,但是由于prototye的类型为any,因此类型信息会丢失。

是否可以正确键入ctor,以便可以在其中看到静态成员?

1 个答案:

答案 0 :(得分:1)

您可以使用tyepof Foo来获取类的实际类型(而不是实例)。这将包含任何静态方法:

var ctor: typeof Foo = undefined as any;

function decorator() {
    return function <T extends typeof Foo>(constructor: T) {
        ctor = constructor;
        return constructor;
    }
}

@decorator()
class Foo {
    static Func = () => console.log("Hi");
}

Foo.Func();
ctor.Func();

不将您绑定到特定类的更通用的方法是将方法添加到构造函数签名中:

interface DecoratableClass {
    new (...a: any[]) : any // replace any with an interface as needed
    Func: ()=> void
}
var ctor: DecoratableClass= undefined as any;

function decorator() {
    return function <T extends DecoratableClass>(constructor: T) {
        ctor = constructor;
        return constructor;
    }
}

@decorator()
class Foo {
    static Func = () => console.log("Hi");
}

@decorator() // error no Func
class BadFoo {
    static NoFunc = () => console.log("Hi");
}

Foo.Func();
ctor.Func();
相关问题