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?
CodePudding user response:
HashMap
contains only unique keys. So you can use simple object and assign array to key:
let hash = {};
hash["bobtail"] = [];
hash["bobtail"].push({ age: 10, 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: 10, name: "miffy" }],
birman: [{ age: 5, name: "moorzik" }],
maine: [{ age: 16, name: "mordred" }],
};