【问题标题】:Declare extensions to a Typescript library声明对 Typescript 库的扩展
【发布时间】:2021-06-15 09:53:51
【问题描述】:

我正在使用SequencyextendSequence() 实用程序向所有序列实例添加自定义方法:

import Sequence, { extendSequence, isSequence } from 'sequency'
import equal from '@wry/equality'

class SequencyExtensions {
  equals<T>(this: Sequence<T>, other: Sequence<T> | Iterable<T>): boolean {
    const as = this.iterator
    const bs = isSequence(other) ? other.iterator : other[Symbol.iterator]()
    while (true) {
      const a = as.next()
      const b = bs.next()
      if (a.done && b.done) return true
      if (a.done !== b.done || !equal(a.value, b.value)) return false
    }
  }
}

extendSequence(SequencyExtensions)

它在开发模式下工作(Next.js开发模式),但是我的IDE(WebStorm)和构建过程都失败并出现错误,说自定义方法不存在:

asSequence([1,2,3]).equals([1,2,3])
                    ^^^^^^
                    TS2339: Property 'equals' does not exist on type 'Sequence '.

我尝试将定义与原始接口合并,并将其与之前实际实现它的代码 sn-p 一起导入,但我遗漏了一些东西,因为 IDE 和 bulid 工具都忽略了它:

declare module 'sequency' {
  interface Sequence<T> {
    /**
     * Returns `true` if this sequence is equal to the other sequence or iterable.
     *
     * @param {Sequence | Iterable} other
     * @returns {boolean}
     */
    equals<T>(this: Sequence<T>, other: Sequence<T> | Iterable<T>): boolean
  }
}

将自定义方法合并到导入接口中的正确方法是什么?

【问题讨论】:

    标签: typescript merge interface


    【解决方案1】:

    我发现了问题。

    由于 Sequence 接口是这样定义的:

    export default interface Sequence<T> ...
    

    我还必须在我的扩展中包含完全相同的导出限定符:

    declare module 'sequency' {
      export default interface Sequence<T> {
      // ^^^^^^^^^^^
        ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 2021-05-03
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2017-01-01
      • 2020-05-15
      相关资源
      最近更新 更多