我可以将数组访问器添加到通用 TypeScript 类吗?

use*_*310 5 arrays generics list typescript

我有一个如下所示的列表类:

class List<T> {
    private _array: Array<T>;

    constructor() {
        this._array = new Array<T>();
    }

    get count() { return this._array.length; }

    public add = (state) => {
        this._array.push(state);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想从类访问内部数组:

var something = list[0];
Run Code Online (Sandbox Code Playgroud)

在 C# 中,我会这样做:

public T this[int index]
    {
        get
        {
            return _array[index];
        }
        private set {}
    }
}
Run Code Online (Sandbox Code Playgroud)

但无论如何我都看不到在 TypeScript 中实现这一点。有没有办法将数组访问器添加到我的类中,使其看起来更像一个通用 List ?

谢谢你的脑力!

Nik*_*off 3

虽然语法有点奇怪,但你可以。请注意,由于 typescript 被编译为 js,因此只有数字和字符串是有效键:

interface IList<T> {
    [index: number]: T
}

interface IMap<T> {
    [index: string]: T
}

interface IMap<K, V> {
    [index: K]: V // Error: Index signature parameter type must be either string or number
}
Run Code Online (Sandbox Code Playgroud)

不过,这有一个技巧。您实际上无法重载该运算符,只能告诉编译器它存在。例如,如果您有一个通用对象希望用作哈希表 - 将其声明为而Map<T>不是any. 数组也是如此。

真正充分利用运算符的唯一可能方法是使用数组或对象作为底层元素,将它们声明为,IList/IMap然后修改它们的属性/原型以添加特定功能。例如,要创建一个可观察数组,请参阅此答案