Home > Net >  Typescript: union of several specific type value combination
Typescript: union of several specific type value combination

Time:07-03

I'm not sure how to summarize the question. Here's what I want to achieve:

I have some api handlers, createA, updateA, deleteA, createB, updateB, ..., and I want to export an object containing all handlers like:

const API = {
  A: {
    CREATE: createA,
    UPDATE: updateA,
    ...
  },
  B: {
    CREATE: createB,
    ...
  },
  ...
}

Then get the handler with a function:

type KeyAction = {
  key: "A" | "B" | "C";
  action: "CREATE" | "UPDATE" | "DELETE"
}
const getHandler = ({key, handler}: KeyAction) => {
  return API[key][action];
}

However, let's say B doesn't have a delete handler, how could I define the type correctly so that this return API[key][action] gives no ts errors?

I have tried

type KeyAction = {
  key: "A" | "C";
  action: "CREATE" | "UPDATE" | "DELETE"
} | {
  key: "B";
  action: "CREATE" | "UPDATE"
}

but no luck.

CodePudding user response:

What about making the function generic?

const getHandler = <
  K extends keyof typeof API, 
  A extends keyof typeof API[K]
>({ key, action }: { key: K, action: A }) => {
  return API[key][action];
}

getHandler({ key: "A", action: "UPDATE" })
getHandler({ key: "B", action: "UPDATE" }) // Error

By defining the generic types K which represents a valid key of API and A which represents a key of API[K] we can silence the error in the function and also get an error when we call the function with invalid parameters.

Playground

  • Related