typescript - 向 Promise 原型添加新方法时出现问题
问题描述
打字稿 3.1.2
我搜索了许多堆栈溢出问题和在线文章,并且我多次看到有关修改现有打字稿类的问题的相同类型的答案,例如String
和Array<T>
,但我似乎无法让这个Promise<T>
类工作。
我已经阅读了所有这些,没有运气:
如何在 Typescript 中扩展字符串原型并在接下来使用它?
这是我当前的代码(我尝试了很多变体):
承诺.d.ts
declare global {
export interface Promise<T> {
catchWrapper(): Promise<T>;
}
}
Promise.ts
Promise.prototype.catchWrapper = function<T>(this: Promise<T>): Promise<T> {
return Promise.prototype.catch.apply(this, [e => {
console.log(`catch wrapper. ${e}`);
}]);
}
(我试过添加export { }
Promise.ts,它没有帮助)
另一个.ts
import '../theDir/Promise'
anAsyncMethod().catchWrapper();
这一切都可以编译,但我不断收到运行时错误:
UnhandledPromiseRejectionWarning: TypeError: anAsyncMethod().catchWrapper is not a function
我的 catchWrapper() 实现是否与编译器的接口声明不匹配?
有想法该怎么解决这个吗?
解决方案
尝试更改内容或更改Promise.d.ts
为:
declare interface Promise<T> {
catchWrapper (): Promise<T>;
}
.d.ts
如果它位于您的rootDir
或typeRoots
配置文件中指定的一个中,也不需要导入。
推荐阅读
- android - 工具使用方法:openDrawer = "bottom"
- c - C 语言 K60 系列 GPIO 键盘
- php - Php mysql - 获取最后几天的值和条目总数
- java - 执行 ApplciationRunner 仅在开发配置文件中运行
- reactjs - 接受 TextArea 和 Input 的 onChange 的 Typescript 和 React 组件
- c - 如何在C中重置字符串
- c# - 带线程的套接字循环
- sqlalchemy - 气流安装 | Ansible
- pandas - 用 cumsum 填充连续的 NaN,在每个连续的 NaN 上加一
- amazon-redshift - 将日期名称转换为数字-例如-星期一到 1