如何在TypeScript中指定任何可更新的类型? [英] How to specify any newable type in TypeScript?

查看:174
本文介绍了如何在TypeScript中指定任何可更新的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过此操作,但不起作用. Foo只是对有效方法的测试. Bar是真正的尝试,它应该可以接收任何新类型,但是Object的子类对此无效.

I tried with this but it doesn't work. Foo is just a test of what works. Bar is the real try, it should receive any newable type but subclasses of Object isn't valid for that purpose.

class A {

}
class B {
    public Foo(newable: typeof A):void {

    }
    public Bar(newable: typeof Object):void {

    }
}

var b = new B();
b.Foo(A);
b.Bar(A); // <- error here

推荐答案

您可以使用{ new(...args: any[]): any; }允许带有构造函数且带有任何参数的任何对象.

You can use { new(...args: any[]): any; } to allow any object with a constructor with any arguments.

class A {

}

class B {
    public Foo(newable: typeof A):void {

    }

    public Bar(newable: { new(...args: any[]): any; }):void {

    }
}

var b = new B();
b.Foo(A);
b.Bar(A);  // no error
b.Bar({}); // error

这篇关于如何在TypeScript中指定任何可更新的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆