0

This should be fairly simple, but I just can't get it sorted - I have the following definition:

export interface IUnit {
    id: number;
    name: string;
    //further members;
}
export class Unit implements IUnit {
    id: number;
    name: string;
    //...
}

export interface IUnits { [id: string]: IUnit; }
export class Units implements IUnits { [id: string]: Unit; }

Now, if I have a variable of the type IUnits, e.g.

var x: IUnits = { 
    "1": {"id": 1, "name": "First"}, 
    "2": {"id": 2, "name": "Second"}
};

, how can I determine the number of it's members? x.length(); does not work. I guess I could use for ... in ..., but this seems horribly inefficient...

Peter Albert
  • 15,882
  • 4
  • 59
  • 83

1 Answers1

2

There's not a Typescript way that makes this any more readable syntax than the loop you mention and one other option.

In modern browsers, you can easily get the list of keys:

var len=Object.keys(x).length;

That does create an array though, so you may just want to use the other syntax.

There are a few options discussed here as well.

You may need to filter out properties that contain functions depending on what you're looking for, if for example you had custom event handlers with callbacks.

Community
  • 1
  • 1
WiredPrairie
  • 54,618
  • 14
  • 105
  • 136