简体   繁体   中英

How can I specify a return type for a $http call with Typescript?

Here's my function so far. I already added an interface for the two input parameters but because of the way that this is coded I really don't know how to deal with the return parameters:

function httpGetQuestion(q: ITestQuestion, action: string) {
    return $http({
        url: '/api/Question/GetByUId/' + q.questionUId + '/' + action,
        method: "GET"
    })
}

also:

httpGetQuestion(q, 'fetch')
    .success(function (data) {

Here is the data that gets returned from the $http call:

    public class Q
    {
        public string Answer { get; set; }
        public string Text { get; set; }
    }

您可以内联:

function httpGetQuestion(q: ITestQuestion, action: string) : ng.IHttpPromise<Q> {

You could use the typing for your return value as ng.IHttpPromise:- Using and interface for your service and adding the interface as typing on your dependency, and adding comments (JSDoc) on your interface methods will give you nice intellisense as well providing the description and other information about the method.

Something like this:-

export interface IMyService{
        /**
         * Returns promise which will resolve to .....
         * @returns {ng.IHttpPromise<Q>}
         */
        httpGetQuestion(q: ITestQuestion, action: string) : ng.IHttpPromise<Q>;
}


class MyService implements IMyService{

 constructor(...
        private $http: ng.IHttpService,
        ...) {

    }

  .....    

   httpGetQuestion(q: ITestQuestion, action: string) {
     return this.$http({
        url: '/api/Question/GetByUId/' + q.questionUId + '/' + action,
        method: "GET"
     });
   }

 ....

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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