强制派生类具有带有预定义签名的构造函数

问题描述 投票:0回答:2

在打字稿中是否可以强制所有派生类都具有带有预定义签名的构造函数?

inheritance typescript1.5
2个回答
3
投票

如果父类的构造函数需要一些参数,开发人员将被迫使用超级构造函数传递这些参数:

class Base {
    constructor(a : string, b : string) {
        // ...
    }
}

class Derived extends Base {
    constructor(a : string, b : string) {
        super(a,b); // Error if super is not invoked
    }
}

如果开发人员没有显式声明

Derived
类构造函数,他们在创建实例时将收到错误:


0
投票

,不可能阻止扩展类对构造函数使用不同的签名。

但是,您可以通过使用静态方法来解决此问题,该方法将为您提供所需的类型安全性:

class A {
  static instantiate<T extends A>(this: { new (...args: ConstructorParameters<typeof A>): T }, ...args: ConstructorParameters<typeof A>): T {
    return new this(...args)
  }

  constructor(foo: number) {}
}

class B extends A {}

const b: B = B.instantiate(3) // Fine

class C extends A {
  constructor(foo: number, bar: boolean) {
    super(foo)
  }
}

const c: C = C.instantiate(3) // Error: The 'this' context of type 'typeof C' is not assignable to method's 'this' of type 'new (foo: number) => A'.

此模式不会阻止重写

constructor
方法,但它可以再次保护父静态方法对子类的不当实例化。

© www.soinside.com 2019 - 2024. All rights reserved.