用于promise.prototype.finally的TypeScript类型定义 [英] TypeScript type definition for promise.prototype.finally

查看:135
本文介绍了用于promise.prototype.finally的TypeScript类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是与ES6 Promise兼容的最终实现,称为 promise.prototype.finally ,但是没有可以在确定输入。在这种情况下,我只为需要的功能子集编写了即兴类型定义,但在这种情况下,它是一个修改Promise对象原型的库,并且我还没有遇到任何常规的方式来表示此类型在TypeScript中。有任何想法吗?



可能相关:




解决方案

尽管Slava的答案是正确的,但仅处理 finally 块的键入。要将垫片实际包含到代码中,因此可以编写 p.finally(()=> {...}),您需要调用垫片。 / p>

不幸的是, DefinitelyTyped 上的键入当前不支持 shim 函数,因此直到支持,我建议您自己添加类型。



 声明接口Promise< T> {
最终U(onFinally ?:()=> U | Promise< U>):Promise U&
}

声明模块‘promise.prototype.finally’{
导出函数shim():void;
}



现在可以使用类型。使用

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

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

 从'promise.prototype.finally'导入{shim}; 
shim();

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


I was using this ES6 Promise compatible finally implementation called promise.prototype.finally in a Node application that I want to convert to TypeScript however there are no typing available for this package that I can find on DefinitelyTyped. In these situations I've written up my own impromptu type definitions for just the subset of functionality that I need but in this case it is a library that modifies the prototype of the Promise object and I haven't encountered any conventional way to represent this in TypeScript. Any ideas?

Possibly related:

解决方案

Whilst the answer from Slava is correct, it only deals with the typing of the finally block. To actually incorporate the shim into your code, so you can write p.finally(() => { ... }), you need to invoke the shim.

Unfortunately the typings on DefinitelyTyped do not currently support the shim function so until this is supported, I'd advise to add the typings yourself.

declare interface Promise<T> {
  finally<U>(onFinally?: () => U | Promise<U>): Promise<U>;
}

declare module 'promise.prototype.finally' {
  export function shim(): void;
}

The types are now available. Install with

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

In your TypeScript code, during application bootstrap, you can then call

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

This will add the finally block to the Promise prototype, allowing you to use finally as required.

这篇关于用于promise.prototype.finally的TypeScript类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆