简体   繁体   English

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

[英]Can I add array accessors to generic TypeScript classes?

I have a list class that looks like this: 我有一个列表类,如下所示:

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);
    }
    ...
}

And I would like to access the internal array from the class: 我想从类中访问内部数组:

var something = list[0];

In c# I would do it something like this: 在c#中,我会这样做:

public T this[int index]
    {
        get
        {
            return _array[index];
        }
        private set {}
    }
}

But I can't see anyway to accomplish this in TypeScript. 但我无法在TypeScript中看到完成此任务。 Is there a way to add array accessors to my class so it looks more like a generic List ? 有没有办法向我的类添加数组访问器,使它看起来更像是一个通用的List?

Thanks for the brainpower! 谢谢你的智慧!

You can though the syntax is a bit weird. 你可以虽然语法有点奇怪。 Note that since typescript gets compiled to js, only numbers and strings are valid keys: 请注意,由于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
}

There's a trick to it though. 但是有一个技巧。 You can't actually overload the operator, you can only tell the compiler that it exists . 你实际上不能重载操作符,你只能告诉编译器它是否存在 For instance if you have a generic object that you wish to use as a hashtable - declare it as Map<T> instead of any . 例如,如果您有一个希望用作哈希表的通用对象 - 将其声明为Map<T>而不是any The same goes for arrays. 数组也是如此。

The only possible way to actually put the operator in good use is to use an array or object as the underlying element, declare them as IList/IMap and then fiddle with their properties / prototype to add specific functionality. 实际操作运算符的唯一可能方法是使用数组或对象作为底层元素,将它们声明为IList/IMap ,然后调整其属性/原型以添加特定功能。 For example, to create an observable array see this answer 例如,要创建一个可观察的数组,请参阅此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM