首页 > 解决方案 > 具有初始值的 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]
]);

但我不喜欢它。

感谢您宝贵的时间和精力!

标签: javascripttypescriptgenericstypestypescript-generics

解决方案


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
]);

推荐阅读