3

I'm a new game developer who started from C#.

Now I need to transfer one of my games to typescript.

I tried to customize a list in typescript which i'm very familiar to in C#. my code is like below:

export class List {

private items: Array;
constructor() {
    this.items = [];
}

get count(): number {
    return this.items.length;
}

add(value: T): void {
    this.items.push(value);
}

get(index: number): T {
    return this.items[index];
}
contains(item: T): boolean{
    if(this.items.indexOf(item) != -1){
        return true;
    }else{
        return false;
    }
}
clear(){
    this.items = [];
}
}

Still, I want to make like a array so I can do things like:

someList[i] = this.items[i];

I guess it's something like operator overload but I'm not quite sure.
Can any one tell me how to make it?
Thanks in advance.

Evan Lyu
  • 33
  • 2

2 Answers2

2

Simply extend Array

export class List<T> extends Array<T> {

    constructor() {
        super();
    }

    get count(): number {
        return this.length;
    }

    add(value: T): void {
        this.push(value);
    }

    get(index: number): T {
        return this[index];
    }

    contains(item: T): boolean {
        if (this.indexOf(item) != -1) {
            return true;
        } else {
            return false;
        }
    }

    clear() {
        this.splice(0, this.count);
    }
}
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

To achieve the effect of overloading the indexing operator, you would have to use a proxy to get the runtime behavior and then use an index signature for the typing, like this:

interface List<T> {
    [n: number]: T;
}

But proxies are serious machinery. You might be better off living with the boilerplate of method calls.

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75