To ensure type safety in the interface I am creating, both keys and values need to be typesafe. Only keys from a defined union-type should be allowed, same goes for values.
This is what I currently have:
// Backend process handling database actions
// returning results to frontend for state update
const eventHandlers = {
updateItems: async (category: "user" | "tracks") => {
// Query database
// Send updated items to event emitter on channel "setItems"
},
addUsers: async (email: "string") => {
// Database operations
// Emit result to frontend on channel "updateUsers"
},
}
type FrontendChannels = "updateUsers" | "setItems"
type BackendChannels = keyof typeof eventHandlers
// How can I enforce type safety for keys and values?
// Keys should be from object keys and values from type `FrontendChannels`
interface BackToFrontChannels {
updateItems: "setItems"
addUsers: "updateUsers"
hi: "mom" // Should not be valid
}
type BackendEventHandler = {
[key in BackendChannels]: {
args: Parameters<typeof eventHandlers[key]>
emitToChannel: BackToFrontChannels[key]
}
}
The BackToFrontChannels
interface lacks type safety indication. How can I improve this?