2015-05-19 30 views
1

我有一个使用AngularJS的项目,并且想要在$http服务之上创建一个包装。我希望我的请求承诺有abort()方法。TypeScript:替换现有类型

如果我写

function request(params:ng.IRequestConfig):my.IRequestPromise { 
    var promise = $http(params).then(onSuccess, onError); 
    promise.abort = function() { // => here it fails with error "Property 'abort' does not exist on type 'IPromise<{}>'" 
    ... 
    } 
    return promise; 
} 

失败与abort定义行。

我写了一个接口IRequestPromise,它通过添加一个abort()方法扩展了ng.IPromise。如何让TypeScript将promise视为my.IRequestPromise而不是ng.IPromise

回答

1

你可以投承诺的类型(ng.IPromise)返回到你的类型(my.IRequestPromiseng.IPromise扩展):

var promise = <my.IRequestPromise<yourreturntype>>$http(params).then(onSuccess, onError); 

假设您的分机是这样的:

export interface IRequestPromise<T> extends ng.IPromise<T> { 
    ... 
} 

还要确保你的函数返回类型也是属性类型,即

function request(params:ng.IRequestConfig):my.IRequestPromise<anyOrSpecificTypeResolvedByPromise> { 
+0

现在它抛出'type'IRequestPromise'不是通用的'。好像我不明白TypeScript的一些重要... – Girafa

+0

您需要返回'unction request(params:ng.IRequestConfig):my.IRequestPromise {'您的界面def看起来像什么'interface IRequestPromise extends ng .IPromise <{}>'? – PSL

+0

我的类型是'IRequestPromise'。我需要将它传递给自己吗? 'my.IRequestPromise '? – Girafa