TypeScript 0.9 Generics:JQueryPromise <t>结果编译为JQueryPromise <any> </any> </t>

时间:2013-07-14 05:54:38

标签: typescript

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

我想调用userService.GetRole()并返回类型JQueryPromise&lt;角色&gt;但它不在这种情况下...它返回JQueryPromise&lt;任何&gt;和intellisense对'role'变量不起作用:

/// <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)
    );

});

以下确实给了我intellisense但我必须输入userService.GetRole&lt;角色&gt;()而不仅仅是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)...等,'role'参数被识别为'Role'类型?

1 个答案:

答案 0 :(得分: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)
    );    
});