账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Typescript该如何往Promise实例增加方法
    51
    0
    let pr = new Promise((r)=>r(1))pr.run = function(){}现在报错Property 'run' does not exist on type 'Promise<unknown>'自己是这么定义的不知道对不对type CustomPromise<T=any> = Promise<T> & {run(): void}let pr:CustomPromise = new Promise((r)=>r(1)) as CustomPromisepr.run = function(){}哪位老哥能指点下感谢
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • ┑树与~阿喵┍ 普通会员 1楼

      在TypeScript中,你可以通过将一个函数包装在Promise实例中,然后在Promise的then方法中调用这个函数来添加方法。以下是一个例子:

      ```typescript interface PromiseAction { (action: any): Promise; }

      interface PromiseExample { (action: PromiseAction): Promise; }

      async function example() { let promise = new PromiseExample(); await promise.example(); // This will call the 'example' method of the PromiseExample object

      // You can also use the same PromiseExample instance in the following way let promise = new PromiseExample(); promise.example(); // This will call the 'example' method of the same PromiseExample instance

      // You can also create your own custom PromiseAction interface interface MyPromiseAction { (action: any): Promise; }

      let myPromiseAction = new MyPromiseAction(); myPromiseAction.example(); // This will call the 'example' method of your custom PromiseAction interface } ```

      在这个例子中,我们定义了两个接口:PromiseActionPromiseExamplePromiseAction接口包含了action参数,PromiseExample接口包含了example方法。example方法是一个异步操作,它返回一个新的Promise实例。在example方法中,我们可以使用await关键字来等待Promise实例的完成。

      PromiseExample接口中,我们可以使用example方法来返回一个Promise实例。这样,我们就可以在PromiseExample接口的then方法中调用这个方法,从而在Promise实例完成时执行一些操作。

      MyPromiseAction接口中,我们可以定义自己的方法example。这样,我们就可以在MyPromiseAction接口的example方法中调用这个方法,从而在MyPromiseAction接口的then方法中执行一些操作。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部