How to create function with dynamic feedback type?

Asked

Viewed 159 times

1

When working with Typescript, I came across a problem. I have a function that returns an object of type ObjetoComposto<any | any[]>, but I would like to define the type of object that will be sent as parameter depending on how the function is called.

The best example of what I want is with a simple data query function on a server using Angular and HttpClient:

getData(): Observable<Modelo[]> {
  return this.http.get<Modelo[]>(PATH);
}

Where the guy Modelo is used to "type" the Observable data that will be sent back. If this is not passed, Typescript will interpret the Observable as Observable<unkown>, or Observable<any>, depending on the received autocomplete package.

In short, I want to be able to pass my object Modelo inside ObjetoComposto by calling the function that way:

getObjeto(): ObjetoComposto<Modelo>{
  return this.objetoCreator.create<Modelo>();
}

1 answer

1


You have to use Generics:

getObjeto<T>(): <T>{
  return this.objetoCreator.create();
}

getData<T>(): Observable<T> {
  return this.http.get<T>(PATH);
}

To call it:

this.getObjeto<SuaInterfaceOuClasse>();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.