[英]Pass class as generic parameter Typescript
我試圖實例化一個作為參數傳遞給另一個類的類,我在一個文件中擁有這個,ImportedClass.ts:
export default class ImportedClass {
public constructor(something: any) {
}
public async exampleMethod() {
return "hey";
}
}
這在另一個 InstanceClass.ts 中:
interface GenericInterface<T> {
new(something: any): T;
}
export default class InstanceClass <T> {
private c: GenericInterface<T>;
public constructor(c: T) {
}
async work() {
const instanceTry = new this.c("hello");
instanceTry.exampleMethod();
}
}
這在另一個 ClassCaller.ts 中:<--EDITED-->
import ImportedClass from './ImportedClass';
import ImportedClass from './InstanceClass';
const simulator = new InstanceClass <ImportedClass>(ImportedClass);
然后當我這樣稱呼它時:
simulator.work();
它拋出這個錯誤:
error TS2339: Property 'exampleMethod' does not exist on type 'T'.
歡迎任何幫助,謝謝。
如果T
必須有一個名為exampleMethod
的方法,則必須將其包含在Simulator
上的T
的約束中,以便能夠在Simulator
使用它:
export class ImportedClass {
public constructor(something: any) {
}
public async exampleMethod() {
return "hey";
}
}
interface GenericInterface<T> {
new(something: any): T;
}
export class Simulator<T extends { exampleMethod(): Promise<string> }> {
public constructor(private c: GenericInterface<T>) {
}
async work() {
const instanceTry = new this.c("hello");
await instanceTry.exampleMethod();
}
}
const simulator = new Simulator(ImportedClass);
simulator.work()
還有其他一些小問題需要修復才能使上述代碼段正常工作,但這是主要問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.