在Promise原型中添加新方法时遇到问题

时间:2018-12-28 07:20:37

标签: typescript

打字稿3.1.2

我搜索了很多堆栈溢出问题和在线文章,并且多次看到关于修改现有打字稿类(例如StringArray<T>)的相同类型的答案,但是我似乎无法在Promise<T>类上使用。

我已经阅读了所有这些内容,没有运气:

How to define global function in TypeScript?

How to add file with extending prototype in Typescript

How to extend String Prototype and use it next, in Typescript?

Cypress Custom TypeScript Command is not a Function

Extending Array in TypeScript


这是我当前的代码(我尝试了许多变体):

Promise.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}`);
        }]);
    }

(我尝试在Promise.ts中添加export { },但无济于事)

another.ts

import '../theDir/Promise'

anAsyncMethod().catchWrapper();

所有这些都可以编译,但是我不断遇到运行时错误:

UnhandledPromiseRejectionWarning: TypeError: anAsyncMethod().catchWrapper is not a function

我的catchWrapper()实现是否与编译器的接口声明不匹配?

关于如何解决此问题的任何想法?

2 个答案:

答案 0 :(得分:1)

尝试将内容或Promise.d.ts更改为此:

declare interface Promise<T> {
  catchWrapper (): Promise<T>;
}

如果.d.ts位于您的rootDir或配置文件中指定的typeRoots之一中,也不需要导入。

答案 1 :(得分:0)

这里的目标是在lib中拥有扩展方法,并在其他应用程序中使用它。在弄乱了一段时间之后,我最终使用了该解决方案。遗漏任何一部分都会导致运行时错误。

通过将声明和定义都放在.ts文件中,然后将文件(在任何地方..!)导入lib中,我的其他项目便能够尽快使用扩展方法它会从库中导入任何内容。

最终代码如下:

在lib项目中:

Promise.ts

Promise.prototype.catchExtension = function<T>(this : Promise<T>): Promise<T> {
    return Promise.prototype.catch.apply(this, [() => { /*do stuff*/ }]);
}

declare global {
    interface Promise<T> {
        catchExtension(): Promise<T>;
    }
}
export { }

lib.ts

import './Promise';
export { } from './Promise';
// The rest of the exports
export { Example } from './Example'

在主应用中:

// Import anything from lib
import { Example } from '@mylib'
// import { } from '@mylib' <--- doesn't work

const x: Promise<string> = new Promise( (resolve, reject) => { reject(); });
x.catchExtension();
// It works! We end up in `() => { /*do stuff*/ }`