小编Eug*_*leo的帖子

如何在 Typescript 4.0.3 中正确扩展数组原型?

我正在尝试Array使用一些自定义方法扩展基本接口。我环顾了 SO 和 typescript 文档,最后将以下代码放在一起:

// In module Func.ts

declare global {
  type Array<T> = {
    intersperse(mkT: (ix: number) => T): T[];
  };
}

if (!('intersperse' in Array.prototype)) {
  Array.prototype.intersperse = function intersperse<T>(this: T[], mkT: (ix: number) => T): T[] {
    return this.reduce((acc: T[], d, ix) => [...acc, mkT(ix), d], []).slice(1);
  };
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

// On type Array<T> = { ... }
Duplicate identifier 'Array'.ts(2300)

// On Array.prototype.intersperse = ...
Property 'intersperse' does not exist on type 'any[]'.ts(2339) …
Run Code Online (Sandbox Code Playgroud)

arrays prototype interface typescript

2
推荐指数
1
解决办法
651
查看次数

标签 统计

arrays ×1

interface ×1

prototype ×1

typescript ×1