当我扩展内置数组 class 时,如何使用实用程序类型或类型参数进行类型推断?

How to get type inference using a utility type, or type parameter, when I extend the built-in array class?


为扩展数组中的 Class 成员定义类型 Class


在下面,您可以看到我通过 WillyWonka class 扩展了数组 class。问题是,当我如下所示执行时,我没有对存储在数组中的项目进行类型推断。

我最担心的是数组原型实现了奇异的属性,使其成为一个特殊的、有点独特的 class 扩展。我正在以与在 JS 中相同的方式扩展它,并使用以下方法将值添加到数组中 Object.assign(this, sumOmpaLoompas);。 还有其他方法可以将项目添加到数组中,我尝试过,但没有获得类型推断。这就是为什么我觉得我应该使用类型参数或实用程序类型。


/*
---------------("DOCUMENT #1")--------------- */
type OmpaLoompa = {
  name: string,
  work: ()=> string
}

type OmpaLoompas = OmpaLoompa[];


class WillyWonka extends Array{
  constructor(sumOmpaLoompas: OmpaLoompas){
    super();
    Object.assign(this, sumOmpaLoompas);
  }
}

const ompaLoompas = [
  {
    name: 'Frank the Frightened Ompa',
    work: ()=> 'Produced Chocolate'
  },
  {

    name: 'Fran the Frail Loompa',
    work: ()=> 'Produced Carmel'
  },
  {
    name: 'Larry the Lazy Ompa',
    work: ()=> 'Didn\'t Produce Today'
  },
  {
    name: 'Linda the Lovely Loompa',
    work: ()=> 'Produced Wafers'
  }
];
/*


---------------("DOCUMENT #2")--------------- */
const wonkyWilly = new WillyWonka(ompaLoompas);
const ompaLoompaAtZero = wonkyWilly[0];
const ompaLoompaAtTwo = wonkyWilly[2];

console.log(ompaLoompaAtZero); //       <-- TYPE = ANY (I need this to be "type: OmpaLoompa")
console.log(ompaLoompaAtTwo.work()); // <-- TYPE = ANY (I need this to be "type: OmpaLoompa.work")

// EXPECTED OUTPUT:
// { name: 'Frank the Frightened Ompa', work: [Function: work] }
// Didn't Produce Today


总结


  1. 在上面的例子中有一个 class WillyWonka 扩展了 Array class.

  2. classes 构造函数接受一个明确定义类型的参数。

  3. 然后Object.assign(...)用于将构造函数参数中的可迭代对象作为属性添加到class,因此可以访问属性,并通过使用迭代扩展数组 class.


这是我的问题


也许我写的 class 有误,老实说,我真的不知道这是否是定义自定义数组对象的最佳方式。它似乎适用于所有意图和目的,除了一个——因为它是 TypeScript,它有点大——Type Inference。我希望 TSC 可以推断类型,以便当我将 WillyWonka class 从一个文档导入到下一个文档时,它会知道 willyWonka[0] 是 [=19= 类型],但 TSC 只是将其注释为 any。如果这不是其他人会使用的API,我可能会处理它,但我必须假设其他人会使用这个Lib/API。所以,在这一点上,如果你一直关注我,那么我的问题应该很简单。

"How can I define the types for the properties on the custom WillyWonka extended array class?"

我愿意使用 Object.assign(...) 以外的其他机制,只要我仍然可以访问 OmpaLoompa 类型的属性作为 willyWonka[i:number]


哦,另一个细节,我希望 classes 被推断为导入的 class,换句话说;

你看到评论“/* DOCUMENT #1 */”和另一个评论“/* DOCUMENT #2 */”了吗?我不能被迫在文档 #2 中输入数组的属性,因为文档二是使用 Lib/API 的示例,我将只写文档 #1。当任意开发人员使用 WillyWonk API.

编写文档 #2 时,我需要已经定义的类型

我是公关

简单修复:只需将 OmpaLoompa 添加到 Array 的通用参数。

class WillyWonka extends Array<OmpaLoompa> { /* ... */ }

否则 TypeScript 将假定 Array 的元素属于 any.

类型