首页 文章

promise.prototype.finally的TypeScript类型定义

提问于
浏览
4

我在一个节点应用程序中使用这个ES6 Promise兼容的最终实现名为promise.prototype.finally,我希望将其转换为TypeScript,但是我在DefinitelyTyped上找不到这个可用的包 . 在这些情况下,我遇到了在TypeScript中表示这种情况的任何传统方式 . 有任何想法吗?

可能相关:

3 回答

  • 14

    虽然Slava的答案是正确的,但它只涉及 finally 块的输入 . 要将填充程序实际合并到代码中,以便编写 p.finally(() => { ... }) ,您需要调用填充程序 .

    不幸的是,DefinitelyTyped上的打字目前不支持垫片功能,所以在支持之前,我建议你自己添加这些打字 .

    声明接口Promise <T> {
    终于<U>(onFinally?:()=> U | Promise <U>):承诺<U>;
    }

    声明模块'promise.prototype.finally'{
    export function shim():void;
    }

    这些类型现在可用 . 安装时

    npm install --save-dev @types/promise.prototype.finally
    

    在TypeScript代码中,在应用程序引导期间,您可以调用

    import { shim } from 'promise.prototype.finally';
    shim();
    

    这会将 finally 块添加到 Promise 原型,允许您根据需要使用 finally .

  • 9

    对于任何想知道如何在没有任何垫片的情况下本地工作的人:从TS 2.7开始,它是可能的 .

    请注意,TS 2.7尚未完全(2018年2月26日)与ES2018兼容 . 虽然还有一些事情missingPromise.finally made it into the 2.7 release . 此外,tsconfig-schema应该已经接受ES2018作为目标,但TS 2.7不了解ES2018 . 现在使用新功能,例如Promise.finally,已经在2.7, you'll have to use "target": "ESNEXT" in your tsconfig.json.

    然后你就可以编写这样的代码了:

    myAsyncFunction().then
    (
      (var) => console.log("executing then. " + var)
    )
    .catch
    (
      (var) => console.log("executing catch. " + var)
    )
    .finally
    (
      () => console.log("executing finally.")
    )
    

    请注意finally will not take any arguments由于它的性质 .

    IMPORTANT :虽然TS会正确转换并理解你在做什么,但仍然需要检查你的JS-Engine是否支持Promise.finally . 在我的情况下,我使用NodeJs 8.x,当然 生产环境 的JS不可执行,因为 Promise.Finally is supported starting with in the latest NodeJs 10.x nightly builds Node 10.x (stable), see this link.

  • 1

    您可以编写自己的d.ts文件并在tsconfig.json文件中引用它 . 你做到这一点,你可以为像你这样的其他人贡献DefinitelyTyped git

    更新:

    如果我正确理解你的意思,你可以在你自己的d.ts文件中扩展现有的 Promise 类 . 使该方法是可选的,因此它不会告诉您实际的 Promise 类没有正确实现接口 . 您需要将其扩展为接口 .

    您的d.ts文件应该如下所示

    declare module 'es6-promise/dist/es6-promise' {
        export interface Promise <R> {
          finally?<U>(onFinally?: () => U | Promise<U>): Promise<U>;
        }
    }
    

    它应该正常工作......

    我为你创建了一个项目作为例子:promise-extension-typescript-example

    我创建了一个对DefinitelyTyped git存储库的pull请求,希望它会被接受,你可以从那里下载它...

相关问题