Amit Chigadani
Amit Chigadani

Reputation: 29715

Accessing indexable object in typescript

I have a following indexable object declared which will contain list of Video Models identified by some key which is a number.

component.ts

private videoItems : {[key: number]: Array<Video>};      // indexable object

constructor(private action: Action, private videoModel: Video) {}

And I have assigned it in the following way in component

this.action.items.forEach(
            (item : Video) => {
                this.videoItems[item.idVideo] = Object.assign(new Video(),this.videoModel);
            }
        );

Video.model.ts

export class Video {

    private _idVideo : number;

    get idVideo (): number {
        return this._idVideo ;
    }

    set idVideo (value: number) {
        this._idVideo = value;
    }
}

If I try to access the videoItems like this.videoItems[12], I get undefined. Where as I if I access it like this.videoItems['12'] I get the video object properly. My question is even though I have declared the key as number and is also set with a number, then why should I access it using a string?

Upvotes: 0

Views: 198

Answers (1)

Horia Coman
Horia Coman

Reputation: 8781

Keys for JavaScript objects must be strings or symbols. The latter is a recent addition. Numbers are coerced to strings, so code like this works:

let x = {}
x[10] = 'foo';
console.log(x[10]); // Prints "foo"
console.log(x['10']); // Prints "foo"
x['20'] = 'bar';
console.log(x[20]); // Prints "bar"

Try it out in the browser or node and see that it does indeed behave that way. It's quite strange that it does not in your case. Perhaps there's something else going on?

Upvotes: 1

Related Questions