简体   繁体   English

Typescript / Angular:静态类引用作为函数参数

[英]Typescript/Angular: static class reference as function parameter

I'm quite new to typescript, and found that mapping an http response to a class was really nifty, like 我对打字稿很陌生,发现将http响应映射到类确实很不错,例如

getMovies(): Observable<Movie[]> {
  return this.http.get<Movie[]>(this.endpoint);
}

returning a populated array of Movie classes (just an example) 返回一个填充的Movie类数组(仅作为示例)

That made me attempt to generalize this somewhat, by calling on a hypothetical get method in a parent class, like 这使我试图通过在父类中调用假设的get方法来对此进行一些概括,例如

// child
getMovies(): Observable<Movie[]> {
  return this.super.get(class_reference_here, this.endpoint);
}

// parent
get(reference: any, endpoint: string): Observable<any> /* or <any[]> ?? */  {
    return this.http.get<reference[]>(endpoint);
}

Is there a way to achieve something like this? 有没有办法实现这样的目标? Is there a way to populate class_reference_here with something sensible? 有没有一种方法可以用一些明智的方法填充class_reference_here Does it spit in the face of Typescript? 它会在打字稿上吐吗? I don't know! 我不知道! Any help is greatly appreciated. 任何帮助是极大的赞赏。

I think you're looking for Generics . 我认为您正在寻找泛型

// child
getMovies(): Observable<Movie[]> {
  return this.super.get<Movie[]>(this.endpoint);
}

// parent
get<T>(endpoint: string): Observable<T> {
    return this.http.get<T>(endpoint);
}

I can't see the point of adding an abstraction layer to httpClient or whatever you are trying to do. 我看不到将抽象层添加到httpClient或您尝试执行的任何操作的意义。 Nevertheless you should have a look at Generics in Typescript . 不过,您应该看看Typescript中的泛型

function identity<T>(arg: T): T {
  return arg;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM