【问题标题】:Declaring types for mixin class为 mixin 类声明类型
【发布时间】:2019-01-16 18:09:11
【问题描述】:

不是 TypeScript 用户,但我正在为我的 JavaScript 库编写一个 TypeScript 声明文件,但我坚持使用以下代码:

function ArrayMixin(Base) {
  class ExtendedArray extends Base {}
  return ExtendedArray;
}

这将返回一个扩展给定类的类。在这种情况下,我想将 Base 限制为 Arrays 和 TypedArrays(所谓的索引集合)。我可以创建一个联合类型来声明所有必要的构造函数并将其用作函数签名中的类型:

type IndexedCollection = ArrayConstructor|Int8ArrayConstructor
declare function ArrayMixin(Base: IndexedCollection): ExtendedArray

但是如何指定我的 ExtendedArray 扩展了 IndexedCollection 中的任何一个?如何声明 ExtendedArray?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    正如 Søren D. Ptæus 建议的那样,对泛型进行更多研究,使我得出以下结论。 为了声明这个 JavaScript 构造:

    function ArrayMixin(Base) {
      class ExtendedArray extends Base {}
      return ExtendedArray;
    }
    

    我们在声明文件中需要这个:

    export declare class ExtendedArray {}
    
    interface Constructor<T> {
        new (...args): T;
    }
    
    export declare function ArrayMixin<T extends IndexedCollection>(Base?: Constructor<T>):
     Constructor<T & ExtendedArray>;
    

    【讨论】:

      【解决方案2】:

      您可以使用generic constraints 指定您的返回类型扩展IndexedCollection,如下所示:

      declare function ArrayMixin<T extends IndexedCollection>(Base: IndexedCollection): T
      

      【讨论】:

      • 谢谢!这可能是一个幼稚的问题,但是我该如何处理类本身,我现在应该如何声明它?
      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 2021-01-04
      • 2016-07-03
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      相关资源
      最近更新 更多