我正在尝试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)