javascript - 具有初始值的 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', 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 无法匹配您提供的签名和参数传递的签名。主要是,值readonly
在 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
]);
推荐阅读
- node.js - 使用 NGINX 反向代理时如何将 HTTP 重定向到 HTTPS?
- javascript - addEventListeners 有什么问题
- flutter - 从预览页面发送照片到 GridView
- firebase - 可以在服务器上的 firestore 事务中修改应用程序状态吗?
- mule - 未知应用程序流显示为已停止,从而阻止 Mulesoft (3.9.1) 应用程序处理请求
- r - 将字符串转换为变量名并将其用于 R 循环中的绘图问题
- python - 检查字典键是否存在并具有价值的有效方法
- java - 在 jar build b Spring Boot 中找不到文件
- algorithm - 查找有多少子字符串的第一个和最后一个字符在内部重复的快速方法
- php - Symfony5 - 动态编辑依赖于级联其他表单的表单