If you want to obtain items using either a string or an index, you'll have to implement a Dictionary. There is no framework class library for TypeScript, so you don't get this for free - just the language features to make one.
You can technically use both string and number indexers, but the first string item is not the same as the first number item. Example:
class Item {
constructor(public name: string) {
}
}
var items = [];
items['a'] = new Item('One');
items['b'] = new Item('Two');
items[0] = new Item('Three');
alert(items['a'].name); // One
alert(items[0].name); // Three
Here is a really basic Dictionary class.
class Item {
constructor(public name: string) {
}
}
class Dictionary<T> {
private items = [];
add(key: string, value: T) {
this.items.push(value);
this.items[key] = value;
}
getByIndex(index: number) {
return this.items[index];
}
getByKey(key: string) {
return this.items[key];
}
}
var dictionary = new Dictionary<Item>();
dictionary.add('a', new Item('One'));
dictionary.add('b', new Item('Two'));
alert(dictionary.getByIndex(0).name);
alert(dictionary.getByKey('a').name);
This also works if you change an item...
dictionary.add('a', new Item('One'));
dictionary.getByIndex(0).name = 'Changed';
alert(dictionary.getByIndex(0).name);
alert(dictionary.getByKey('a').name);
[0]can easily be automatically converted into a string as a key, or stays numeric for offset. Better to make something like anelementAt(offset)method to do the offsetting. Also, why are you getting the first element of a dictionary? By definition, a dictionary shouldn't have any order... Are you trying to enumerate all the elements in the dictionary? In that case, you probably should be using afor inloop.