How to declare and initialize an empty array of objects

I’m trying to declare an array of objects to add new objects later. I’m doing this away:
private arrayOfObjects: [{}];

When I try to push some object to it I receive the following error:

Cannot read property ‘push’ of undefined

I believe this is because the array needs to be initialized. If I initialize it like a normal array:
private arrayOfObjects: [{}] = [];

I get another error:

Property ‘0’ is missing in type ‘[ ]’ but required in type ‘[{}]’.

So if I declare the array this way:
private arrayOfObjects: [{}] = [{}];

I can now push objects to it, but I get an empty object in the beginning of the array. I can easily remove this object from the array, but I really want to know how I can do it correctly. I could not find any similar problem in here or in SO.

Object structure: {name: string, active: boolean}

So, how can I declare and initialize an array of objects without the empty object in it?

private arrayOfObjects= [];

As you do not type the objects itself (which is a pity btw), you should try the easiest route.

I feel really dumb now, I tried to initialize this way, but declaring the type as a normal array :sweat_smile:

private arrayOfObjects: [] = [];

In the end I was doing this way and deleting the first object:

private submenus: [{name:string, active:boolean}] = [{name:'', active:false}];

The urge to declare the type of every variable… Well, thank you!

private submenus: {name:string, active:boolean}[] = [];

should work too and is at least a bit more typed then not typed at all

2 Likes

…is a really great and productive urge. The problem here is that it didn’t get followed enough, I think. Please keep reading the rest of the thread, because @Tommertom’s later post is better than the one accepted as the solution ATM.

1 Like