Home > Software design >  Create interface / type with restricted keys and values
Create interface / type with restricted keys and values

Time:07-17

Playground link

I want to create an interface (or type) which keys and values are themselves "typesafe". For example, I should only be able to set keys which are within an union-type and the same goes for the values.

So I have this:

// Backend process handling the database
// and returning its results to the frontend to update its state

const eventHandlers = {
  updateItems: async (category: "user" | "tracks") => {
    // Do database queries
    // Send updated items to event emitter on channel "setItems"
  },
  addUsers: async (email: "string") => {
    // Do database queries
    // Emit result to frontend channel "updateUsers"
  },
}

type FrontendChannels = "updateUsers" | "setItems"
type BackendChannels = keyof typeof eventHandlers

// How can I make the keys and values typesafe?
// The keys should derived from the object and the values from the type `FrontendChannels`
interface BackToFrontChannels {
  updateItems: "setItems"
  addUsers: "updateUsers"
  hi: "mom"      // Should not work
}

type BackendEventHandler = {
  [key in BackendChannels]: {
    args: Parameters<typeof eventHandlers[key]>
    emitToChannel: BackToFrontChannels[key]
  }
}

The BackToFrontChannels interface is not typesafe and will not warn me very well when my code needs adjustments. How can I fix this?

CodePudding user response:

We can map over the elements inside BackendChannels.

type BackToFrontChannels = {
  [K in BackendChannels]: FrontendChannels
}

Playground

  • Related