我正在为我的公司做一个前端项目,在这个项目中,我们从API中查询不同的对象(比如用户、产品等等)。
我目前正试图概括我们的服务,这些服务处理组件和API之间的数据传输,因为它们几乎都是这样做的(试图保持它的干燥状态)。为了实现这一点,我需要根据泛型的类型进行不同的API调用。
基本上可以归结为:
public foo<TMyType>(){
if (TMyType === TypeA) {
//do stuff
} else if (TMyType === TypeB) {
//do other stuff
} else {
throw new Error('Invalid type');
}
}注意,我不想传递实际的对象,而只是根据调用函数的泛型类型来决定要做什么。我觉得应该有一个很简单的方法来实现这一点,但我想不出来。
非常感谢
发布于 2022-09-08 13:49:28
不能在运行时进行类型比较,但可以这样做:
function foo<T extends TypeA | TypeB>(a: T) {
}T extends TypeA | TypeB意味着泛型T只能是TypeA或TypeB。
要将typeA与typeB区分开来,您必须找到一个可以区分它们的特定属性
例如:
type TypeA = string
type TypeB = { test: string }
function foo<T extends TypeA | TypeB>(a: T) {
if(typeof a === "string") {
//... a is TypeA
} else if("test" in a) {
//... a is TypeB
}
}发布于 2022-09-08 13:55:22
您可以删除一些具有类继承的样板。
class GenericRestService {
protected endpoint: string = '/stuff';
constructor(protected httpClient: HttpClient) {}
makeACall<T>(param: string): Observable<T> {
return this.httpClient.get<T>(`${this.endpoint}/${param}`)
.pipe(
// some stuff here
);
}
}class SpecificRestService extends GenericRestService {
endpoint = '/otherThings';
}https://stackoverflow.com/questions/73649842
复制相似问题