如何解决TypeScript Map类构造函数,其初始值不接受2种不同类型
首先,我正在使用以下类:
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',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',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',2);
const food_backpack = new Map<Student,Food>([
[sam,cheese],[ariana,chocolate]
]);
但是我不喜欢它。
感谢您的宝贵时间和精力!
解决方法
TypeScript无法匹配您提供的签名和参数传递的签名。 Mainly,the values are readonly
in a Map
。
您可以创建一个新类型,例如
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 page所看到的,它采用这样的参数:
new Map([
[1,'one'],[2,'two'],[3,'three'],])
所以它是一个由两个元素组成的数组。第一个元素是键,第二个是值。因此,它完美地解释了为什么可以使用:
new Map<Student,Food>([
[sam,cheese],[ariana,chocolate]
])
但现在具有:
new Map<Student,bi_ariana
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。