我目前正在使用 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”类型?