2

I have this child class :

export class ChildService extends ParentService {
  protected model = ChildModel;
}

In the parent, I would like to use the child's model as a type for the response of a http call, and for the promise !

getData(): Promise<this.model> { // doesn't work
  return this.http.get(this.url)
    .toPromise()
    .then(response => response as this.model) // doesn't work
    .catch(this.handleError);
}

Is it possible ?

1 Answer 1

1

Use type generics.

export class ChildService extends ParentService<ChildModel> {
}

class ParentService<TType> {
   getData(): Promise<TType> {
      return this.http.get(this.url)
     .toPromise()
         .then(response => response as TType)
         .catch(this.handleError);
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That looks awesome !
What if another function in the same class needs to use another type ?
@JeremyBelolo can you give me an example? You can use more than one type for generics <TTypeA, TTypeB, TTypeC>. Methods can also have their own local types getData<DataType>: Promise<DataType> {...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.