【问题标题】:How to specify any newable type in TypeScript?如何在 TypeScript 中指定任何新的类型?
【发布时间】:2016-01-18 08:50:48
【问题描述】:

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

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

【问题讨论】:

    标签: typescript method-signature newable


    【解决方案1】:

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

    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】:

      如果你只想强制执行某些新变量,你可以指定构造函数的返回类型

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

      等价

      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;
      }
      

      测试

      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
      };
      

      【讨论】:

      • 请注意,AnyError extends Error 的这种方法非常适用于这种情况,因为 Error 在内部没有作为 Class 类型,因此不能简单地用作右侧的 typeof Error
      猜你喜欢
      • 2022-12-25
      • 2020-01-23
      • 2021-06-18
      • 1970-01-01
      • 2019-02-03
      • 2019-12-12
      • 2020-06-21
      • 1970-01-01
      • 2021-06-03
      相关资源
      最近更新 更多