HashMap with List as a value in Typescript

Viewed 1202

I am learning TypeScript and am trying to create a collection similar to the following in Java

HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>();

I am unable to find any examples . Is it possible to do this in Typescript? Is there something similar to this?

1 Answers

HashMap contains only unique keys. So you can use simple object and assign array to key:

let hash = {};
hash["bobtail"] = [];
hash["bobtail"].push({ age: 7, name: "miffy" });
console.log(hash)

Or try to use Record<Keys, Type>. As docs says:

Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

interface CatInfo {
  age: number;
  name: string;
}
 
type CatBreed = "bobtail" | "birman" | "maine";
 
const cats: Record<CatBreed, CatInfo[]> = {
  bobtail: [{ age: 7, name: "miffy" }],
  birman: [{ age: 8, name: "moorzik" }],
  maine: [{ age: 17, name: "mordred" }],
};

UPDATE:

This is the way to add an item to Record<Keys, Type>:

cats["bobtail"].push({ age: 11, name: "miffy" });

This is the way to get items from Record<Keys, Type>:

const bobtails: CatInfo[] = cats["bobtail"];
Related