【问题标题】:Problem adding a new method to Promise prototype向 Promise 原型添加新方法时出现问题
【发布时间】:2018-12-28 07:20:37
【问题描述】:

打字稿 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 { },但没有帮助)

另一个.ts

import '../theDir/Promise'

anAsyncMethod().catchWrapper();

这一切都可以编译,但我不断收到运行时错误:

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

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

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

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

    【讨论】:

    • 我遇到了与该代码相同的错误。但是,该代码无需export { } 语句即可编译。
    • 另外,你不需要import是正确的
    • 我最终无法使用这种代码风格。我通过实验找到了一个解决方案,我已经在下面发布了。
    【解决方案2】:

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

    通过将声明和定义都放在 .ts 文件中,然后在 lib 中导入 file(任何地方..!),我的另一个项目就可以立即使用扩展方法它从库中导入任何东西。

    这是最终代码的样子:

    在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*/ }`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      相关资源
      最近更新 更多