javascript - TypeScript:替换现有类型

标签 javascript angularjs typescript

我有一个使用 AngularJS 的项目,想要在 $http 服务之上制作一个包装器。我希望我的请求 promise 具有 abort() 方法。

如果我写

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 定义线上失败。

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

最佳答案

您可以将返回的 Promise 类型 (ng.IPromise) 强制转换为您的类型(从 ng.IPromise 扩展的 my.IRequestPromise) :

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> {

关于javascript - TypeScript:替换现有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328854/

相关文章:

javascript - 带有特殊字符 (.) 的正则表达式字边界 javascript

javascript - 不一致的 Date.now() 值

javascript - 从数组值返回对象键

javascript - numberOfLines TextInput 属性不起作用

javascript - AngularJs ui.bootstrap 问题 - 折叠不起作用

javascript - AngularJs 如何将参数传递给 $scope.$apply?

javascript - 从复选框创建搜索过滤器数组(Ionic Framework)

typescript - 在 VS Code 中调试不适用于 Typescript Vue 应用程序

angular - Angular 6/Typescript 中的广播事件

javascript - 更改 typescript 断点后无法正确设置,并且 main-client.js 不断将自身加载到 Visual Studio 2017 中