2

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

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

export interface 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?

1 Answer 1

3

I think you want something like this:

export interface Room {
    users: UserMap;
}

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

export interface 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer! I was not sure what I should search in google though. Now I remember it's a map type.
Sure, index signatures are meant to model map-like objects in JavaScript, but it's not obvious what they'd be called. Hopefully someone searching finds this answer. As a heads up, if all you're using these for is the type, you can use an interface declaration instead of a class (since interfaces don't have any emit).
You're right. I forgot to mention the interface, it was quickly written example without much thinking and was tired. Thanks for advise! P.S edited the question, replaced class with interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.