【发布时间】:2021-05-10 13:28:37
【问题描述】:
问题是:
我有一个类,它有一些方法可以进行特定的 api 调用。此类获取作为构造函数参数的接口,其中有一组方法用于将 API 响应转换为其他内容。但是从API类的角度来看,没有必要知道transformer的实现,这样就可以以任何方式实现transformer。我想做的是在实例化所有内容后知道返回的类型。
所需行为的代码示例
type SomeObj = {
stringKey: string;
numberKey: number;
}
type SomeOtherObj = {
stringKey: string;
numberKey: number;
}
function fetch1() {
return { stringKey: 'stringKey', numberKey: 2 }
}
function fetch2() {
return { stringKey: 'stringKey', numberKey: 2 }
}
interface IATransformer {
transformResOne: (res1: SomeObj) => any;
transformResTwo: (res2: SomeOtherObj) => any;
}
class ATransformer {
transformResOne(res1: SomeObj): string {
return res1.stringKey
}
transformResTwo(res2: SomeOtherObj): number {
return res2.numberKey;
}
}
interface IA<T extends ATransformer> {
getOne: (param: string) => any; // Not "any" but something from the generic
getTwo: (param2: string) => any; // Not "any" but something from the generic
}
class A<T extends ATransformer> implements IA<T> {
constructor(
private readonly transformer: T
) { }
// Return type doesn't work in this way but don't know how to sobstitute it
getOne(param: string): ReturnType<this.transformer.getOne> {
const res = fetch1()
return this.transformer.transformResOne(res)
}
// Return type doesn't work in this way but don't know how to sobstitute it
getTwo(param2: string): ReturnType<this.transformer.getTwo> {
const res = fetch2();
return this.transformer.transformResTwo(res)
}
}
const transformer = new ATransformer();
// Generic is inferred from the parameter
const a = new A(transformer);
// Desired result ---> ERROR: the type returned from the function is not number but string
const resOneResult: number = a.getOne('Some string')
我已经尝试过使用泛型,我的最佳猜测是这样的:
class A implements IA {
constructor(
private readonly transformer: IATransformer
) { }
getOne(param: string): ReturnType<typeof this.transformer.transformResOne> {
const res = fetch1()
return this.transformer.transformResOne(res)
}
getTwo(param2: string): ReturnType<typeof this.transformer.transformResTwo> {
const res = fetch2();
return this.transformer.transformResTwo(res)
}
}
当然不行!
【问题讨论】:
-
这根本不使用泛型——你没有声明任何泛型类型参数。
-
请考虑修改此问题中的代码以构成minimal reproducible example,将其放入像The TypeScript Playground (link to code) 这样的独立IDE 中时,可以清楚地说明您面临的问题。 (例如,唯一存在的错误应该是您遇到的错误;不应该有未声明的类型或值。)这将允许那些想要帮助您立即着手解决问题的人,而无需首先重新 -创造它。它将使您得到的任何答案都可以针对定义明确的用例进行测试。
-
@jcalz 这就是重点,我不知道我想做的事情到底怎么写,上面的表示是我能做的最好的。
-
@kaya3 使用泛型更新了代码,这里的重点是我不明白正确使用它们来获得所需结果的热。我使用我尝试过的方式更新了代码,但是,我知道,编译会到处抱怨
标签: typescript typescript-typings typescript-generics