Nika Nika - 1 month ago 15
TypeScript Question

How to declare iterable object of another interface type?

So, here I'm trying to make interface type of Object which will contain only specific interfaces in it. For example:

export class IUser {
name: string;
last: string;
};

export class IRoom {
users: Object<IUser>; // this is wrong.
}


I'm expecting, that users will be something like:

Users: {
'user_id_goes_here': {
name: 'John',
last: 'Doe'
},
'user_id_goes_here': {
name: 'Albert',
last: 'Einstein'
},
...
}


Is there any way to define interface member type like this?

Answer

I think you want something like this:

export class Room {
    users: UserMap;
}

export class UserMap {
    [userId: string]: User;
}

export class User {
    name: string;
    last: string;
}    

That [userId: string]: IUser; is what's called a string index signature. It means that whenever you use a string to index into a UserMap, you will get an IUser.