Chris
Chris

Reputation: 472

Typescript definitions for string enum key indexed objects?

I have the following enum and data models defined:

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,
}

I define my data as below:

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' },
}

This works, but does not enforce specific types per object. Instead it enforces the union of the three types, Location | Person | Vehicle.

Is it possible to enforce the specific object type to match the enum index key? If so, how can it be done?

For example, I would like the 3rd location object to fail type checking, because the Location interface does not have a firstname variable. It seems like I am missing the mapping between the enum Models and the individual interfaces but I am not sure. Any help is appreciated. Thanks.

Upvotes: 2

Views: 90

Answers (1)

Chris
Chris

Reputation: 472

I ended up creating a mapping between the interfaces and the enum as follows:

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

Upvotes: 3

Related Questions