1

There was a problem studying the typescript.

How to specify a declared interface as the type of map?

exmaple code)

interface User {
  id: number;
  name: string;
  age: number;
  house: {
    id: number;
    address: string;
    ...,
    ...
  }
  ...,
  ...
}


const userMap = new Map<User>();  // a different motion than expected...
quakka-ju
  • 31
  • 1
  • like this `const userMap = new Map();` ? – Tobias S. May 17 '22 at 12:01
  • You are asking for a heterogeneous map, so I'd ask you to reconsider why you would need a map here. – kelsny May 17 '22 at 13:47
  • See the answer to the linked question for more information. Using that code here gives [this](https://tsplay.dev/mZGgeW). I have yet to hear a compelling use case for why someone would want to use a `Map` instead of a plain object like `User` or maybe `Partial`, so you should really think about what you're trying to do. – jcalz May 17 '22 at 14:05

1 Answers1

0

Map Generics require either 0 or 2 parameters.

If you want the value of the Map to be the User interface, and assuming you want a string as the key, you can do as follows:

const userMap = new Map<string, User>();
Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • Thank you for a good idea. But what I want is that the key and value of the interface are used as key and value in the map. – quakka-ju May 17 '22 at 12:44