【问题标题】:Extending Promise base class typings扩展 Promise 基类类型
【发布时间】:2021-01-25 15:46:57
【问题描述】:

我正在尝试使用静态方法和实例方法扩展 Promise 基类。 我在打字稿定义方面遇到问题。 请参阅下面的代码!

declare global {
    class PromiseConstructor {
        static timeout(): null;
    }
    interface Promise<T> {
        timeout(): null
        finally<T>(f: () => void): Promise<T>,
    }

}

Promise.timeout = (n: number) => {
  // code...
}

Promise.prototype.finally = function (onFinally) {
  // code...
};

使用此代码,当我尝试在上面定义 Promise.timeout 时,打字稿给了我错误:Property timeout is a static member of type PromiseConstructor

如果我尝试在 interface Promise 块内定义输入 timeout(),打字稿会给我错误 'static' modifier cannot appear on a type member

如何输入超时方法?

【问题讨论】:

  • 请不要在全局变量上粘贴新函数,制作一个模块并从那里导入函数。
  • 我还在做 :)
  • 完全同意@Bergi:不要这样做)

标签: javascript typescript ecmascript-6


【解决方案1】:

据我所知,您必须从 interface PromiseConstructor 扩展而不是 class PromiseConstructor

declare global {
  interface PromiseConstructor {
    timeout(n: number): any;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2019-10-22
    • 2022-07-12
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多