gpt4 book ai didi

javascript - 将类作为泛型参数传递给 Typescript

转载 作者:行者123 更新时间:2023-11-30 20:02:53 27 4
gpt4 key购买 nike

我正在尝试实例化一个作为参数传递给另一个类的类,我在一个文件 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()

Playground link

还有其他小问题需要修复才能使上面的代码片段正常工作,但这是主要问题。

关于javascript - 将类作为泛型参数传递给 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com