我定义了以下枚举和数据模型:

const enum Models {
  Location = 'Location',
  Person = 'Person',
  Vehicle = 'Vehicle'
}

export interface Location {
  name?: string,
  city?: string,
  state: string,
  zip?: string,
}

export interface Person {
  firstname: string,
  lastname?: string,
}

export interface Vehicle {
  model: string,
  year?: string,
}

我的数据定义如下:
type ModelMap = {[key in Models]: Location | Person | Vehicle}

const data: ModelMap = {
  [Models.Location]: { state: 'CA' },
  [Models.Location]: { state: 'OR' },
  [Models.Location]: { state: 'CO', firstname: 'blah' },
  [Models.Person]: { firstname: 'John', lastname: 'Doe' },
  [Models.Vehicle]: { model: 'Ford', year: '2018' },
}

这是可行的,但不会强制每个对象使用特定类型。相反,它强制执行三种类型的联合,即位置人员车辆。
是否可以强制特定对象类型与枚举索引键匹配?如果是,怎么办?
例如,我希望第三个location对象的类型检查失败,因为location接口没有firstname变量。似乎我缺少枚举模型和各个接口之间的映射,但我不确定。如有任何帮助,我们将不胜感激。谢谢。

最佳答案

我最终在接口和枚举之间创建了一个映射,如下所示:

type EnumInterfaceMap = { Location: Location; Person: Person; Vehicle: Vehicle };
type ModelMap = {[key in Models]: EnumInterfaceMap[key]}

10-04 22:52
查看更多