First things first, I'm using these classes:
class Student {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Food {
flavor: string;
portions: number;
constructor(flavor: string, portions: number) {
this.flavor = flavor;
this.portions = portions;
}
}
Basically what I'm doing is that:
const food_backpack = new Map<Student, Food>()
const sam = new Student('Sam', 15);
const ariana = new Student('Ariana', 18);
const cheese = new Food('Fetta', 5);
const chocolate = new Food('Twix', 2);
food_backpack.set(sam, cheese);
food_backpack.set(ariana, chocolate);
Well that worked.
But I'm trying to use the constructor instead to initialize the map values which IS NOT WORKING for me (compile time errors). I tried this below:
const sam = new Student('Sam', 15);
const ariana = new Student('Ariana', 18);
const cheese = new Food('Fetta', 5);
const chocolate = new Food('Twix', 2);
const bi_sam = [sam, cheese];
const bi_ariana = [ariana , chocolate];
const food_backpack = new Map<Student, Food>([
bi_sam,
bi_ariana
]);
And this below:
const sam = new Student('Sam', 15);
const ariana = new Student('Ariana', 18);
const cheese = new Food('Fetta', 5);
const chocolate = new Food('Twix', 2);
const bi_sam = [(sam as Student) , (cheese as Food)];
const bi_ariana = [(ariana as Student) , (chocolate as Food)];
const food_backpack = new Map<Student | Food, Food | Student>([
bi_sam,
bi_ariana
]);
Something that uses the constructor way and THAT WORKED is:
const sam = new Student('Sam', 15);
const ariana = new Student('Ariana', 18);
const cheese = new Food('Fetta', 5);
const chocolate = new Food('Twix', 2);
const food_backpack = new Map<Student, Food>([
[sam, cheese],
[ariana, chocolate]
]);
But I don't prefer it.
Thanks for your precious time and effort!