Typescript 扩展Array.prototype

Typescript 扩展Array.prototype,typescript,Typescript,我可以扩展Array.prototype并在javascript中使用它,如下所示: Object.defineProperty(Array.prototype, 'flatten', { value: function flatten() { return this.reduce((a, b) => a.concat(b), []); } }); // that allows me to do: [1, 2, [3, 4]].flatten(); // [1,2,3

我可以扩展Array.prototype并在javascript中使用它,如下所示:

Object.defineProperty(Array.prototype, 'flatten', {
  value: function flatten() {
      return this.reduce((a, b) => a.concat(b), []);
  }
});

// that allows me to do:
[1, 2, [3, 4]].flatten(); // [1,2,3,4]
[1, 2, [3, 4]].map(e => 5).flatten(); // [5, 5, 5]
但是,在typescript下,我得到一个错误:类型“Array[]”上不存在属性“flatte”。

我可以避免像下面这样做,但要获得一个流畅的界面并不好……它更难阅读

 (<any>[1, 2, [3, 4]]).flatten()
 ([1, 2, [3, 4]].map(e => 5) as any).flatten()
([1,2,3,4]])。展平()
([1,2[3,4]].map(e=>5)如有).flatten()

我可以在typescript中做些什么来避免对任何类型的转换吗?喜欢动态了解类型脚本,而类型数组的代码有另一种方法。

您可以扩展
数组
界面,添加
展平
方法:

declare global {
    interface Array<T> {
        flatten(): T[]
    }
}
声明全局{
接口阵列{
展平():T[]
}
}

请注意,仅当您在模块中时,才需要将其包装在
声明全局中。请参见

您可以扩展
数组
界面以添加
展平
方法:

declare global {
    interface Array<T> {
        flatten(): T[]
    }
}
声明全局{
接口阵列{
展平():T[]
}
}
请注意,仅当您在模块中时,才需要将其包装在
声明全局中。看