[英]Typescript define generic constructor function
我正在嘗試將Typescript與具有psuedo類的JS庫一起使用,該庫具有提供繼承的extend()
函數。 我被困在如何將不同的構造函數傳遞給新的“類”:
type A = (param1: string, param2: number);
type B = (param3: number, param4: number);
interface BaseClass {
extend<Constructor>(): {
new(); // How would I associate this function with type Constructor?
}
}
var NewClass = BaseClass.extend<A>();
new NewClass('Hello world', 3); // type checked against type A
var SecondClass= BaseClass.extend<B>();
new SecondClass(4, 5); // type checked against type B
我已經試過了:
interface BaseClass {
extend<Constructor>(): {
new(): Constructor;
}
}
但這希望new NewClass()
返回類型A。
我已經試過了:
interface BaseClass {
extend<Constructor>(): {
new<Constructor>();
}
}
但是,這不會鍵入check new NewClass()
。
將函數與類型相關聯的正確語法是什么?
找出了new()
構造函數的解決方法。 我更改了類型以包含new
關鍵字本身:
type A = {
new(param1: string, param2: number);
}
type B = {
new(param3: number, param4: number);
}
然后,我可以從extend()
調用返回構造函數,如下所示:
interface BaseClass {
extend<Constructor>(): Constructor;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.