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 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

I already have this approach in my class. I thought there may be a direct way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.