HashMap
ensures that keys are unique. You can easily assign an array to a key using a simple object:
let hash = {};
hash["furry"] = [];
hash["furry"].push({ age: 4, name: "fluffy" });
console.log(hash)
Alternatively, you can utilize Record<Keys, Type>
. According to the documentation:
Generates an object type with specified property keys as Keys and corresponding
property values as Type. This feature allows mapping properties of one type to another.
interface DogInfo {
age: number;
name: string;
}
type DogBreed = "husky" | "poodle" | "corgi";
const dogs: Record<DogBreed, DogInfo[]> = {
husky: [{ age: 5, name: "shadow" }],
poodle: [{ age: 2, name: "bella" }],
corgi: [{ age: 10, name: "rover" }],
};
UPDATE:
To add an item to Record<Keys, Type>
, follow this approach:
dogs["husky"].push({ age: 8, name: "max" });
To retrieve items from Record<Keys, Type>
, use this method:
const huskies: DogInfo[] = dogs["husky"];