How to specify any newable type in TypeScript?

痞子三分冷 提交于 2019-12-19 03:18:13

问题


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

回答1:


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



回答2:


If you want to enforce only certain newables, you can specify the constructor's return type

interface Newable {
  errorConstructor: new(...args: any) => Error; // <- put here whatever Base Class you want
}

equivalent

declare class AnyError extends Error { // <- put here whatever Base Class you want
  // constructor(...args: any) // you can reuse or override Base Class' contructor signature
}

interface Newable {
  errorConstructor: typeof AnyError;
}

testing

class NotError {}
class MyError extends Error {}

const errorCreator1: Newable = {
  errorConstructor: NotError, // Type 'typeof NotError' is missing the following properties from type 'typeof AnyError': captureStackTrace, stackTraceLimitts
};

const errorCreator2: Newable = {
  errorConstructor: MyError, // OK
};


来源:https://stackoverflow.com/questions/33224047/how-to-specify-any-newable-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!