2

I am implementing the Typescript Array interface. I wonder if there is any possibility to define the get/set for indexes. For example:

class MyClass<T> implements Array<T> { 
  [index: number] : T; 

  // ... other methods
}

Is there a possibility to write in a following way:

class MyClass<T> implements Array<T> { 
  get [index: number] () : T { 
     // implementation 
  } 
  set [index: number] (value: T) : void { 
     // implementation 
  } 

  // ... other methods
}

1 Answers1

1

No, overloading the index operator cannot be done on classes; however, you can define this with an ES6 Proxy, but many browsers don't support that yet.

One alternative is to create a wrapper around an array in order to force people to use the methods, where you can put additional functionality:

class MyContainer<T> { 
    private items: T[] = [];

    get(name: string): T { 
        // some additional functionality may go here
        return this.items[name];
    } 

    set(name: string, value: T) : void {
        // some additional functionality may go here
        this.items[name] = value;
        // or here
    }
}

const myContainer = new MyContainer<string>();
myContainer.set("key", "value");
console.log(myContainer.get("key")); // "value"
Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178