Home > Back-end >  TypeError: Cannot redefine property of extended Array declaration
TypeError: Cannot redefine property of extended Array declaration

Time:08-26

The following code is extending the global Array definition:

// array.ts
export {}

declare global {
  interface Array<T> {
    binaryIndexOf(e: T, desc: boolean): number
    addSorted(e: T, desc: boolean): T[]
  }
}

if (!Array.prototype.binaryIndexOf) {
  Object.defineProperty(Array.prototype, 'binaryIndexOf', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function binaryIndexOf<T>(this: T[], e: T, desc: boolean) {
...

The compiler doesn't complain about missing functions but when I run my code I get the following error

TypeError: Cannot redefine property: binaryIndexOf

   at src/array.ts:36

  34 |
  35 | if (!Array.prototype.addSorted) {
> 36 |   Object.defineProperty(Array.prototype, 'binaryIndexOf', {
     |          ^
  37 |     enumerable: false,
  38 |     writable: false,
  39 |     configurable: false,

If I set the configurable flag to true then another error occurs when trying to invoke addSorted

TypeError: testData.addSorted is not a function

CodePudding user response:

You code in array.ts probably not run if you do not import it in some way.

You need to find a way to execute that polyfill code.

  • Related