mysticalstick
mysticalstick

Reputation: 2559

Typescript: using Object.keys to iterate over a dictionary

So I have this interface for my dictionary and I initialize it below.

export interface IHash {
    [tagName: string] : string;
}

var x : IHash = {};
x["first"] = "details";
x["second"] = "details";

I run let keys = Object.keys(x); and then print my keys and I get 0 1. It looks as if it's outputting the indices. I was expecting it to print first and second. Would I have to loop through it to get that result?

Upvotes: 3

Views: 4233

Answers (1)

Paarth
Paarth

Reputation: 10377

How are you doing your printing of keys? This is what I see in ts-node

> export interface IHash {     [tagName: string] : string; }  var x : IHash = {}; x["first"] = "details"; x["second"] = "details";
'details'
> Object.keys(x);
[ 'first', 'second' ]
>

which suggests the error is with your printing rather than the value of keys.

Are you perhaps calling Object.keys twice in series? The first time it would give you [ 'first', 'second' ] and the second time it would give you [ '0', '1' ]

Upvotes: 3

Related Questions