Reputation: 87
If I have something like:
var treeArray: TreesArray;
treeArray = [new tree("Maple"),
new tree("Pine"),
new tree("Spruce")];`
How do I alert the 2nd member?
This doesn't work: alert(treeArray[1]);
Update: Sorry, I should have included the full code from the beginning. The alert, as I've written it, still doesn't work.
interface ITrees{
treeName: string;
}
interface TreesArray{
[index: number]: ITrees;
length: number;
}
class tree implements ITrees{
treeName: string;
constructor (treeName: string){
this.treeName = treeName;
}
}
var treeArray: TreesArray;
treeArray = [new tree("Maple"),
new tree("Pine"),
new tree("Spruce")];
alert(treeArray([1]);//does not alert "Pine"
Upvotes: 2
Views: 124
Reputation: 251192
If you have a wrapper (you have called it TreesArray
in your question), you need to ensure that the wrapper defines an indexer.
interface TreesArray {
[index: number]: tree;
}
Here is a complete example:
class tree{
constructor(public treeName: string){
}
}
interface TreesArray {
[index: number]: tree;
}
var treeArray: TreesArray;
treeArray = [
new tree("Maple"),
new tree("Pine"),
new tree("Spruce")
];
alert(treeArray[1].treeName);
Upvotes: 0
Reputation: 276235
It does work:
class tree{
constructor(public treename){
}
toString(){return this.treename}
}
var treeArray: tree[];
treeArray = [new tree("Maple"),
new tree("Pine"),
new tree("Spruce")];
alert(treeArray[1]);
You will get:
Upvotes: 1