[英]TypeScript - How do you infer a class generic type from a method's parameter?
[英]typescript method with type as parameter
鑒於此類層次結構
export class A {
static m() { return 'a'};
}
export class B extends A {
static m() { return 'b'};
}
export class C extends A {
static m() { return 'c'};
}
我需要一個方法,采用擴展A
的類數組(不是實例)並在數組的每個元素上調用m()
:
function looper(classes: A[]) {
classes.forEach(c => c.m());
}
這需要 A 或其子類的實例數組。
我怎樣才能有一個方法作為擴展 A 的參數類?
@Oscar Paz 指出的泛型
編輯 1
此外,looper 的輸入需要存儲在對象的屬性中:
export class Container {
public klazzes: A[];
}
好吧,使用泛型:
function callM<T extends typeof A>(arr: T[]): void {
arr.forEach(t => t.m());
}
現在你可以這樣做:
callM([A, B, C]); // OK
callM([A, B, string]); // Error
如果要存儲值:
class Container {
public klazzes: (typeof A)[];
}
const cont: Container = new Container();
callM(cont.klazzes);
不確定這是否是您正在尋找的東西 - 在@Oscar 建議的基礎上,您可以創建一個泛型類來將數組存儲在T[]
類型的屬性中,如下所示。
export class A {
static m() { return 'a'};
}
export class B extends A {
static m() { return 'b'};
}
export class C extends A {
static m() { return 'c'};
}
export class Container<T extends typeof A> {
public klazzes: T[];
constructor() {
this.klazzes = [];
}
public callM<T extends typeof A>(arr: T[]): void {
arr.forEach(t =>
console.log(t.m())
);
}
}
// usage
let cont = new Container();
cont.klazzes = [A, B, C];
cont.callM(cont.klazzes);
這是一個工作鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.