2

我目前正在使用 TypeScript 0.9.0.1 并在进行 AJAX 调用时使用 JQueryPromise 接口。我刚刚开始实现新的泛型功能,并注意到在调用具有被调用函数中设置的类型的泛型函数时我没有得到智能感知。

我想调用 userService.GetRole() 并返回类型 JQueryPromise< Role > 但它在这种情况下不...它返回 JQueryPromise< any > 并且智能感知不适用于“角色”变量:

/// <reference path="../declarations/jquery.d.ts" />

interface Role {
    Id: number;
    Name: string;
}

module Services {

    export class UserService {

        //Non-Generic Call
        GetRole<Role>(): JQueryPromise<Role>{
            return $.get('/url');
        }

    }

}

$(function () {

    var userService = new Services.UserService();

    //GetRole() is returning JQueryPromise<any> and not JQueryPromise<Role> as declared
    userService.GetRole().then((role) =>
        //role is inferred as type 'any' and not 'Role' so intellisense does not work
        console.log(role.Name)
    );

});

以下确实给了我智能感知,但我必须输入 userService.GetRole< Role >() 而不仅仅是 userService.GetRole():

/// <reference path="../declarations/jquery.d.ts" />

interface Role {
    Id: number;
    Name: string;
}

module Services {

    export class UserService {

        //Generic Call
        GetRole<T>(): JQueryPromise<T> {
            return $.get('/url');
        }

    }

}

$(function () {

    var userService = new Services.UserService();

    userService.GetRole<Role>().then((role) =>
        //Intellisense now works but I have pass the type '<Role>' every call
        console.log(role.Name)
    );

});

所以我的问题是: 有没有办法让调用 userService.GetRole().then((role) ...etc. 将“role”参数识别为“Role”类型?

4

1 回答 1

1

取决于您希望泛型变得活跃的级别。例如,您可以将其移至您的班级:

module Services {

    //Generic Class
    export class UserService<T> {    

        GetRole(): JQueryPromise<T> {
            return $.get('/url');
        }    
    }    
}

$(function () {

    var userService = new Services.UserService<Role>();

    // You don't need role in every call anymore 
    userService.GetRole().then((role) =>
        console.log(role.Name)
    );    
});
于 2013-07-14T06:43:26.897 回答