JMM
JMM

Reputation: 87

In TypeScript how do I access the member of an array?

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

Answers (2)

Fenton
Fenton

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

basarat
basarat

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]);

Try it online by pressing run

You will get:

enter image description here

Upvotes: 1

Related Questions