首先,我使用这些类:
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;
}
}
基本上我正在做的是:
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);
这很管用。
但我试图使用构造函数来初始化映射值,这对我来说不起作用(编译时错误(。我在下面尝试过:
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
]);
下面是:
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
]);
使用构造函数方式并且有效的东西是:
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]
]);
但我不喜欢。
感谢您宝贵的时间和精力!
TypeScript无法匹配您提供的签名和参数传递的签名。这些值主要是Map
中的readonly
。
你可以创建一个新的类型,比如
type StudentRecord = readonly [Student, Food];
现在您的Map
构造函数应该按预期工作:
const sam = new Student('Sam', 15);
const ariana = new Student('Ariana', 18);
const cheese = new Food('Fetta', 5);
const chocolate = new Food('Twix', 2);
type StudentRecord = readonly [Student, Food];
const bi_sam: StudentRecord = [sam, cheese];
const bi_ariana: StudentRecord = [ariana , chocolate];
const food_backpack = new Map<Student, Food>([
bi_sam,
bi_ariana
]);
正如我们在Map mdn页面上看到的那样,它采用如下参数:
new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
])
这是一个由两个元素组成的数组。第一个元素是键,第二个元素是值。因此,它完美地解释了为什么它与一起工作
new Map<Student, Food>([
[sam, cheese],
[ariana, chocolate]
])
但现在有了:
new Map<Student, Food>([
bi_sam,
bi_ariana
])